将孩子的stdout传递给父母stdin

时间:2013-11-27 00:36:28

标签: c fork pipe stdout stdin

我尝试将子进程中的程序的stdout传递给父进程中的stdin。

在bash中,这将是这样的:

wget“adress”| 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]应该是一个webadress。 但是在运行程序时,父项中dup2(int c2 = dup2(fd[0],STDIN_FILENO);)的调试输出返回-1 - 所以它失败了。

我找不到该程序。

1 个答案:

答案 0 :(得分:3)

您不在程序中致电pipe(2)。我想,你的

int pipe(int fd[2]);

应该是

pipe(fd);