从C程序中执行程序

如何在我的C程序中运行另一个程序,我需要能够将数据写入STDIN(执行程序时我必须通过stdin不止一次提供输入)编程的启动(并逐行读取) STDOUT)

我需要解决方案在Linux下工作。

通过网络我发现下面的代码:

#include  #include  #include  void error(char *s); char *data = "Some input data\n"; 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 %d\n", 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",buf); exit(0); } void error(char *s) { perror(s); exit(1); } 

但是如果我的C程序(需要执行usng exec)只从stdin读取一次输入并返回输出一次,那么这段代码工作正常。但是如果我的Cprogram(需要执行usng exec)输入多次输入(不知道确切地从stdin读取输入的次数)和显示输出放mork比一次(当执行显示输出逐行stdout)然后此代码崩溃。 任何机构都可以建议如何解决这个问题? 实际上我的C程序(需要执行exeng exec)逐行显示一些输出,并且根据输出我必须在stdin上提供输入,并且这个读/写的数量不是常数。

请帮我解决这个问题。

您可以使用select api在读取/写入文件描述符时收到通知。 所以你基本上把你的读写调用放到一个循环中,并运行select以找出外部程序何时消耗了一些字节或者向stdout写了一些内容。