【发布时间】:2013-11-27 00:36:27
【问题描述】:
我尝试将子进程中程序的标准输出传递给父进程中的标准输入。
在 bash 中看起来像这样:
wget "地址"|less
我的代码如下所示:
int fd[2];
pid_t child_id;
int status;
char *args[] = {"wget","-O -",argv[1], NULL};
int pipe(int fd[2]);
child_id = fork();
if (child_id == -1)
{
printf ("Fork error\n");
}
if (child_id == 0)
{
close(fd[0]);
int c = dup2(fd[1],1);
execl ("/usr/bin/wget", "wget", "-qO-",argv[1], NULL);
}
else{
waitpid(child_id,&status,0);
close(fd[1]);
int c2 = dup2(fd[0],STDIN_FILENO);
printf("%i\n",c2 ); //debugging
execl ("/usr/bin/less", "less", NULL);
}
请注意 argv[1] 应该是一个网络地址。
但是在运行程序时,父级中 dup2 (int c2 = dup2(fd[0],STDIN_FILENO);) 的调试输出返回 -1 - 所以它失败了。
我找不到程序。
【问题讨论】:
-
不确定这是否是答案,但在这种情况下不会使用管道特殊文件帮助?
-
附带说明,您可能对
popen()感兴趣。 -
我知道有办法不重定向标准输入/输出,但我想这样做
-
你检查过
errno看看为什么 dup2 失败了吗? -
您不想要
waitpid。如果孩子必须写入比管道容纳的更多的数据,它将阻塞写入并且永远不会终止。只需跳过waitpid并让两者同时运行。 (虽然您不应该让孩子成为孤儿,但在处理其输出之前,您不能为它wait)