如何从我的C程序中运行另一个程序,我需要能够将数据写入STDIN(同时执行程序,我必须通过stdin提供多次输入)编程启动(并从它的STDOUT逐行读取)从C程序中执行程序
我需要解决方案在Linux下工作。
,同时通过网络去,我发现下面的代码:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
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", 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);
}
,但如果我的C程序(需要执行USNG EXEC)从标准输入读取输入一次该代码是工作的罚款,并返回输出 一次。但如果我的C程序(需要执行usng exec)正在输入多次(不知道它会从标准输入读取输入的次数) 和显示输出放置一次(当执行显示输出行由在标准输出上) 然后这段代码崩溃了。任何机构可以建议如何解决这个问题? 其实我的C程序(需要执行usng exec)显示一些输出线,并根据输出我必须提供输入stdin 和此读/写的数量不是恒定的。
请帮我解决这个问题。
/*由于数据量小,孩子可能会阻止,除非我们关闭它的输入流。这将EOF发送给 * stdin的孩子。 */ 你不这样做? – hroptatyr 2010-08-13 09:51:52
请参阅http://stackoverflow.com/questions/3475682/execute-program-from-within-a-c-program 你为什么要问同样的问题两次的任何理由? – hroptatyr 2010-08-13 11:01:16
詹姆斯,再次问同样的问题不会得到你的答案。您可以修改您的问题,或者询问更具体的问题以获得更好的答案,但复制相同的问题不会对您有所帮助。你可能会发现你得到了更多的回应,如果你1)保持你的问题简明扼要,2)不要在其中投入大量的代码。 – Will 2010-08-13 11:26:55