简体   繁体   中英

How to redirect stdout to stdin for a subprocess?

It's been forever since I've used C so I apologize for the simple question.

I'm working with GPIO on a armeabi-v7a device. I need to export the GPIO interface into userspace from within an android app and I am trying to do so from a JNI library.

To do this from the terminal I would just run echo 199 > /sys/class/gpio/export

But I need to do it from JNI :(

My current attempt looks like this (with some error handling), but does not work:

JNIEXPORT jboolean JNICALL Java_com_rnd_touchpanel_LED_exportGreen
    (JNIEnv * je, jclass jc)
{
    freopen("/sys/class/gpio/export", "w+", stdout);
    printf("198");
    fclose(stdout);
    return JNI_TRUE;
}

I then realized that export is actually binary not just a file, and I've forgotten how to spawn new processes and send them input and all that. Could someone refresh my memory? Thanks!

If you're just writing a file, there's no need to redirect stdout -- just open the file with fopen(3) , write to it with fprintf(3) , and close it with fclose(3) .

If you need to execute another process with given data on its standard, you have a few options:

  • Use system(3) to invoke the shell and give it your desired redirections
  • Use popen(3) with type "w" and fprintf your data to the returned FILE*
  • Use fork(2) and exec*(3) to spawn the new process. After forking but before exec'ing, use pipe(2) , dup2(2) and close(2) to setup the new process's stdin appropriately. You can then write to that file descriptor from the parent process to setup the data. This is the most complicated option, but it gives you the most control over how the child process is setup.

It's been a while isnce I've done much C/C++ but I believe spawning a new process is done via popen. Eg:

FILE* pOutput = popen("/usr/bin/python myscript.py", "r");
  while ( fgets(line, 199, pOutput) )
  {
    printf("%5d: %s", entry++, line);
  }

From another post on S/O it seems you can write to the FILE* returned by popen if you open the proc in write mode:

FILE * file = popen("/bin/cat", "w");
fwrite("hello", 5, file);
pclose(file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM