简体   繁体   English

如何将stdout重定向到子进程的stdin?

[英]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. 自从我使用C语言以来,这一直都是如此,因此我为这个简单的问题表示歉意。

I'm working with GPIO on a armeabi-v7a device. 我正在armeabi-v7a设备上使用GPIO。 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. 我需要从android应用程序中将GPIO接口导出到用户空间,而我正在尝试从JNI库中导出。

To do this from the terminal I would just run echo 199 > /sys/class/gpio/export 要从终端执行此操作,我只需运行echo 199 > /sys/class/gpio/export

But I need to do it from JNI :( 但是我需要从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) . 如果您只是在编写文件,则无需重定向stdout -只需使用fopen(3)打开文件,使用fprintf(3)写入文件,然后使用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 使用system(3)调用shell并为其提供所需的重定向
  • Use popen(3) with type "w" and fprintf your data to the returned FILE* popen(3)与类型"w"并将数据fprintf到返回的FILE*
  • Use fork(2) and exec*(3) to spawn the new process. 使用fork(2)exec*(3)生成新进程。 After forking but before exec'ing, use pipe(2) , dup2(2) and close(2) to setup the new process's stdin appropriately. 分叉之后但执行之前,请使用pipe(2)dup2(2)close(2)适当地设置新进程的标准输入。 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. 我已经做了很多C / C ++,这已经有一段时间了,但是我相信可以通过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: 在S / O上的另一篇文章中,如果您以写入模式打开proc,似乎可以写入popen返回的FILE *:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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