Search code examples
c++forkwaitpipeline

fork() 2 children with pipeline, error when wait() for both


I have the following code fork()'s 2 children from a common parent and implements a pipeline between them. When I call the wait() function in the parent once only the program runs perfectly. However if I try to call the wait() function twice (to reap from both the children), the program does nothing and must be force exited.

Can someone tell me why I can't wait for both children here?

int main()
{
    int status;
    int pipeline[2];
    pipe(pipeline);

    pid_t pid_A, pid_B;

    if( !(pid_A = fork()) )
    {
        dup2(pipeline[1], 1);
        close(pipeline[0]);
        close(pipeline[1]);
        execl("/bin/ls", "ls", 0);
    }

    if( !(pid_B = fork()) )
    {
        dup2(pipeline[0], 0);
        close(pipeline[0]);
        close(pipeline[1]);
        execl("/usr/bin/wc", "wc", 0);
    }

    wait(&status);
    wait(&status);
}

Solution

  • You need to close both ends of the pipe in the parent after you fork the children. The problem is that output of ls is going to the parent, and the wc is waiting for input. So the first wait cleans up the ls, but the second is waiting for wc which is blocked on a pipe that's not receiving data.