0
votes

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
Not sure if that is the answer but won't using a pipe-special file help in this case?unxnut
As a side note, you might be interested in popen().FatalError
I know there is way without redirecting the stdin/out but I want to do it like thisarnoapp
did you check errno to see why dup2 failed?evil otto
You do not want the waitpid. If the child has to write more data than will fit in the pipe, it will block on a write and never terminate. Just skip the waitpid and let the two run concurrently. (Although you shouldn't allow the child to become an orphan, you cannot wait for it before you process its output)William Pursell

1 Answers

3
votes

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

int pipe(int fd[2]);

should be

pipe(fd);