Question

I am trying to code a shell pipe in c but my program don't wait all child before finish.

int fd[2];
if (fork() == 0)
{
    dup2(fd[1], 1);
    close(0);
    execlp("ls", "ls, NULL);
}
if (fork() == 0)
{
    dup2(fd[1], 1);
    close(0);
    execlp("wc" "wc", NULL);
}
wait(NULL);//this dont wait all child
//wait(NULL); wait(NULL); this go into infinite loop
//while (wait(NULL) > 0); this go into infinite loop
write(1, "test", 4);

If I use wait(NULL), "test" is displayed in the middle of wc's output and if I use while (wait(NULL) > 0); it goes into an infinite loop.

Edit : The solution was to close the pipe (close(fd[0]); close(fd[1]);) before the wait. I'll edit again if I understand how this work.

Was it helpful?

Solution

Each call of wait(2) blocks the parent-process untill one of its children exits. So if you want to block the parent-process untill all children exit, you have to call wait() in a for loop as many times as your children processes are.

while (wait(NULL) > 0) won't work because wait() returns the PID of the child-process caught, so it's always true, causing an infinite loop.

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