我应该如何从我的C程序运行另一个程序? 我需要能够将数据写入启动的程序的STDIN (也许从STDOUT读取)
我不确定这是否是一个标准的C函数。 我需要在Linux下工作的解决scheme。
铛交叉编译为ARM?
UWP应用程序使用Windows.Devices.WiFi
在Windows中的特定地址分配数据?
如何在Web应用程序中设置主题?
你想用popen 。 它给你一个单向的管道,你可以访问程序的标准输入和标准输出。
popen是现代unix和unix类操作系统的标准,其中Linux是一个:-)
类型
man popen
在终端阅读更多关于它。
编辑
是否popen生产单向或双向管道取决于实施。 在Linux和OpenBSD中 , popen生成单向管道,这些管道是只读的或只写的。 在OS X上 , FreeBSD和NetBSD popen生成双向管道。
我为其他人写了一些示例C代码,显示了如何做到这一点。 这是给你的:
#include <sys/types.h> #include <unistd.h> #include <stdio.h> void error(char *s); char *data = "Some input datan"; main() { int in[2],out[2],n,pid; char buf[255]; /* In a pipe,xx[0] is for reading,xx[1] is for writing */ if (pipe(in) < 0) error("pipe in"); if (pipe(out) < 0) error("pipe out"); if ((pid=fork()) == 0) { /* This is the child process */ /* Close stdin,stdout,stderr */ close(0); close(1); close(2); /* make our pipes,our new stdin,stdout and stderr */ dup2(in[0],0); dup2(out[1],1); dup2(out[1],2); /* Close the other ends of the pipes that the parent will use,because if * we leave these open in the child,the child/parent will not get an EOF * when the parent/child closes their end of the pipe. */ close(in[1]); close(out[0]); /* Over-write the child process with the hexdump binary */ execl("/usr/bin/hexdump","hexdump","-C",(char *)NULL); error("Could not exec hexdump"); } printf("Spawned 'hexdump -C' as a child process at pid %dn",pid); /* This is the parent process */ /* Close the pipe ends that the child uses to read from / write to so * the when we close the others,an EOF will be transmitted properly. */ close(in[0]); close(out[1]); printf("<- %s",data); /* Write some data to the childs input */ write(in[1],data,strlen(data)); /* Because of the small amount of data,the child may block unless we * close it's input stream. This sends an EOF to the child on it's * stdin. */ close(in[1]); /* Read back any output */ n = read(out[0],buf,250); buf[n] = 0; printf("-> %s",buf); exit(0); } void error(char *s) { perror(s); exit(1); }
使用pipe(...)创建两个管道,一个用于stdin ,另一个用于stdout 。
fork(...)的过程。
在子进程( fork(...)返回0) dup (...)到stdin / stdout的管道中。
exec[v][e]要在子进程中启动programm文件。
在父进程中( fork )返回子进程的PID)做一个从子进程stdout ( select(...)或poll(...) , read(...) )读入的循环,缓冲区,直到孩子终止( waitpid(...) )。
最终在stdin提供输入的孩子,如果它期望一些。
当完成close(...)管道。
我不同意纳森费尔曼 – 另一个问题是不是重复的,虽然这个问题是相关的。
对于简单的单向通信,popen()是一个体面的解决方案。 但是,双向通信是没有用的。
国际海事组织(IMO),豪尔赫·费雷拉(Jorge Ferreira)给出了双向交流的大部分答案(80%?),但省略了一些关键细节。
父进程关闭用于将消息发送到子进程的管道的读取结束是非常重要的。
子进程关闭用于将消息发送到子进程的管道的写入结束是非常重要的。
父进程关闭用于将消息发送到父进程的管道的写入端是至关重要的。
子进程关闭用于将消息发送到父进程的管道的读取结束是非常重要的。
如果不关闭管道的未使用端,当其中一个程序终止时,您不会收到明智的行为。 例如,孩子可能正在从其标准输入读取,但是除非管道的写入结束在孩子中关闭,否则它将永远不会得到EOF(从读取的零字节),因为它仍然打开管道并且系统认为它可能有时候会写信给那个管道,尽管它现在正在等待某些东西来读取它。
写入过程应考虑是否处理在没有读取过程的管道上写入时给出的SIGPIPE信号。
您必须了解管道容量(依赖于平台,可能只有4KB)并设计程序以避免死锁。
我想你可以使用
freopen
为了这 。
您可以使用系统调用,阅读系统的手册(3)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。