Question

I've just recently learned about pipes and I would like to emulate the "|" gimmick provided by shells.

In the code below, the parent process spawns 2 child processes, after which they do their piping and get replaced by ls and grep. While that happens the parent process waits patiently. The problem is that the child processes never finish although they manage to send some data though the pipe and onto the screen.

There are other posts regarding pipes on SO, but I've never seen the setup in which the parent process launches 2 children. I've only seen the parent communicating with one child.

int p0[2];
pipe(p0);         //creating pipe

if(fork() == 0) { //child 1
    dup2(p0[0], STDIN_FILENO);
    close(p0[0]); close(p0[1]);
    execlp("grep","grep","a",NULL);
} 
else {            //parent
    if(fork() == 0) { //child 2
        dup2(p0[1], STDOUT_FILENO);
        close(p0[0]); close(p0[1]);
        execlp("ls","ls",NULL);
    }
    else {    //parent
        wait(NULL);
        wait(NULL); //waiting for c1 and c2

        close(p0[0]); close(p0[1]);
        printf("parent exit\n");
    }
}

My questions are: Why don't the child processes finish? Is fork-pipe structure sound or am I doing it completely wrong?

Was it helpful?

Solution

Close the pipe before starting to wait in the last section.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top