How can you wait until all children and grand-children have exited, without blocking in a signal handler? This is my attempt so far.
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int run = 1;
void handler(int sig, siginfo_t *info, void *uap)
{
int exit_code;
printf("sigchld pid %d
", info->si_pid);
pid_t pid = waitpid(-1, &exit_code, 0);
if (pid == -1) {
perror("waitpid()
");
} else {
printf("waitpid returned %d
", pid);
}
// set run = 0 when all children exit
printf("end of sigchild handler
");
}
void main() {
struct sigaction chld;
chld.sa_sigaction = handler;
chld.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
sigaction(SIGCHLD, &chld, NULL);
//procmask sigchld?
if (!fork ()) {
if (!fork ()) {
sleep(2);
printf ("grand-son exit: %d
", getpid());
exit (0);
}
sleep(1);
printf ("son exit: %d
", getpid());
exit (0);
}
while(run)
sleep(1);
printf("ciao
");
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…