【问题标题】:Pass stdout of child to parents stdin将孩子的标准输出传递给父母标准输入
【发布时间】: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

标签: c fork pipe stdout stdin


【解决方案1】:

你没有在你的程序中调用pipe(2)。我猜,你的

int pipe(int fd[2]);

应该是

pipe(fd);

【讨论】:

  • 真的!多么愚蠢的错误 - 谢谢你!
猜你喜欢
  • 1970-01-01
  • 2018-05-04
  • 2019-04-05
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 2015-01-06
  • 2013-09-18
相关资源
最近更新 更多