I'm doing some parallel programming (multiprocessing) and I need the parent to:
1) Fork
several children
2) AFTER all the children have been created, simply WAIT for all of them to terminate
3) After all the children are terminated, do some other work.
This is what I tried:
int main(int argc, char **argv[])
{
int j, i;
pid_t children[3];
int pid;
// Fork the processes
for(j = 0; j < 3; j++){
if((children[j] = fork()) == 0){
// Child process
for(i = 0; i < 2; i++){
printf("child %d printing: %d\n", j, i);
}
}else {
// In parent now
while (pid = waitpid(-1, NULL, 0)) {
if (errno == ECHILD) {
break;
}
}
printf("all children terminated. in parent now\n");
}
}
return 0;
}
Doesn't give the correct output. "all children terminated. in parent now" gets printed out several times, even before all the children are dead. Also, for each process, I should see only 2 outputs, but I see more. Any help would be appreicated.
Is this more what you are trying to achieve? I've just set a simple count for each child with a delay to increase the parallelisation visibility.
The output I get is
Ken
Each child is executing the loop and forking. You need to break out of the
j
loop after printing output. Since those grandchildren are not children of the original parent, and the first generation children are never waiting for them, the order of output is unspecified. Also, you need to bring thewaitpid
out of the j loop and not execute it until all the children have been forked.