Pass stdout of child to parents stdin

孤者浪人 提交于 2019-12-13 04:54:44

问题


I try to pass the stdout of an program in a child process to the stdin in the parents process.

In bash this would look like this:

wget "adress"|less

My code looks like this:

    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);
    }

Please note that argv[1] should be an webadress. But when running the program the debug output of the dup2 (int c2 = dup2(fd[0],STDIN_FILENO);) in the parent returns -1 - so it fails.

I can't find the programm.


回答1:


you do not call pipe(2) in your program. I guess, your

int pipe(int fd[2]);

should be

pipe(fd);


来源:https://stackoverflow.com/questions/20230838/pass-stdout-of-child-to-parents-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!