Question

I want simple and elegant solution for parent process wait for all of his children. I have the following code, but it doesn't work how I want and I don't know why. Can someone explain to me, why?

pid_t pid;
for (int i = 0; i < N; i++) {
    if ((pid = fork()) == -1) 
       return -1; // error, returning from parent
    else if (pid == 0) {
        printf("child: %d\n", pid);
        exit(0); // child i has finished 
    }
    else if (pid > 0) {
        waitpid(-1, NULL, __WALL); // waiting for all children, clone or non-close
        printf("I'm parent. All children have finished.\n"); 
        return 0; // everything OK, returning from parent
    }
 }

My output is:

child: 0
I'm parent. All children have finished.
child: 1
I'm parent. All children have finished.
child: 2
and so on

I want this:

child: 0
child: 1
.
.
.
I'm parent. All children have finished.

Why __WALL option doesn't work for me?

Was it helpful?

Solution

In your code, in each loop the parent-process is creating a child-process; the child-process is printing its message, while the parent-process is waiting for this specific child-process's exit status to be collected before re-entering the loop. Working like this, i+1-th child-process won't be created until i-th child-process terminates.

To see what you expected, your code could look like this (although not using __WALL option here):

pid_t pid;

for (int i = 0; i < N; i++) {
    if ((pid = fork()) == -1) 
       return -1; // error, returning from parent
    if (pid == 0) {
        printf("child: %d\n", i);
        exit(0); // child i has finished 
    }
}

for (i = 0; i < N; i++)
    waitpid(-1, NULL, 0); // waiting for all children

printf("I'm parent. All children have finished.\n");

In this case, the parent-process will first create N processes before it starts to collect their exit status. When it finishes waiting, the proper message will be printed.

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