Instead of calling waitpid
in the signal handler, why not create a loop after you have forked all the processes as follows:
while (pid = waitpid(-1, NULL, 0)) {
if (errno == ECHILD) {
break;
}
}
The program should hang in the loop until there are no more children. Then it will fall out and the program will continue. As an additional bonus, the loop will block on waitpid
while children are running, so you don’t need a busy loop while you wait.
You could also use wait(NULL)
which should be equivalent to waitpid(-1, NULL, 0)
. If there’s nothing else you need to do in SIGCHLD, you can set it to SIG_IGN.