【发布时间】:2010-08-13 09:44:34
【问题描述】:
如何从我的 C 程序中运行另一个程序,我需要能够将数据写入程序启动的 STDIN(在执行程序时我必须多次通过 stdin 提供输入)(并通过来自它的 STDOUT 的行)
我需要在 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 程序(需要使用 exec 执行)只从标准输入读取一次输入并返回输出,则此代码工作正常 一次。但是如果我的 C 程序(需要使用 exec 执行)不止一次地接受输入(不知道它会从标准输入读取多少次) 并显示输出不止一次(执行时在标准输出上逐行显示输出) 那么这段代码就崩溃了。任何机构都可以建议如何解决这个问题? 实际上,我的 C 程序(需要使用 exec 执行)正在逐行显示一些输出,并且根据输出,我必须在 stdin 上提供输入 并且这个读/写的数量不是恒定的。
请帮我解决这个问题。
【问题讨论】:
-
/* 由于数据量小,孩子可能会阻塞,除非我们 * 关闭它的输入流。这会在它的 * stdin 上向孩子发送一个 EOF。 */ 你不这样做怎么样?
-
见stackoverflow.com/questions/3475682/… 你为什么要两次问同一个问题?
-
james,再问同样的问题不会给你答案。您可以修改您的问题或询问更具体的问题以获得更好的答复,但复制粘贴相同的问题对您没有帮助。如果您 1) 让您的问题保持简洁和简短,并且 2) 不要在其中投入大量代码,您可能会发现您会得到更多回复。