4

Is popen not supported by android NDK?

I read this page and wondering if this is true

The same is possible with POSIX popen() but it is not currently supported by bionic, so you can't use that in Android JNI. Instead you can probably use the system() and pipe the output to a file and then read that file afterwards. Looks like the Java approach will be cleaner if you will be doing the rendering in Java.

But I also read someone suggesting to use popen. I also tried it myself but sometime my app crashes and I dont know why.

Is popen safe to use in android ndk?

Phonon
  • 12,549
  • 13
  • 64
  • 114
kuchi
  • 840
  • 11
  • 19

2 Answers2

7

I think it depends on what version of the NDK you are using

Also looking in the gingerbread source tree for bionic I did find an implementation of popen. The implementation might not be 100% posix of libc correct, but it is at least functional to some degree.

Using NDK v6, the following example compiles without any problems, and it runs on my android device.

#include <stdio.h>
#include <stdlib.h>
int main()
{
 FILE *fpipe;
 char *command="/system/bin/ps";
 char line[256];
 if ( !(fpipe = (FILE*)popen(command,"r")) ) exit(1)
 while ( fgets( line, sizeof line, fpipe))
 {
   puts(line);
 }
 pclose(fpipe);
}

UPDATE: Seems than popen on pre ICS versions used vfork() instead of fork(), and those vfork() are known to cause stack corruption.

So from ICS onward popen should be save to use, but on earlier android versions it is available but verry buggy.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
aiah
  • 96
  • 1
  • 4
4

Indeed, popen() will not work on Android. As GLIBC description states, any UNIX operating system needs a C library to make all system calls. These include threading memory allocation, working with files, etc. Because Android is based on Linux, it needs such library implemented, but because it's a small mobile OS, Google decided to write a "lite version" of libc called bionic. This library does not include popen(), therefore you can't use it. There is a description of bionic library in the NDK documentation which lives inside your NDK directory (for some reason it's not online). Hope this helps.

Phonon
  • 12,549
  • 13
  • 64
  • 114
  • Thanks. I am just wondering how come it does work on my sample app? I believe if its not included then it should not work at all. – kuchi Jan 19 '12 at 04:46
  • 1
    Yes, this is correct. Although popen() function is available on Android, it actually corrupts a stack since vfork() approach is used. – Ales Teska Apr 08 '15 at 13:48
  • for me, popen/pclose worked when I called them less than 4-5 times. I wasted so much time on this. – Paschalis Sep 09 '15 at 02:37
  • @ales-teska do you know it that is still the case? Cause I am facing really strange bugs with `popen()` on android and it is a year 2019... – Slava Oct 25 '19 at 13:44
  • @Slava - nope, we don't use that on Android – Ales Teska Oct 25 '19 at 14:07