#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
void func(int signo)
{
pid_t wpid;
int status;
while ((wpid = waitpid(-1, &status, 0)) != -1)
{
if (WIFEXITED(status))
{
printf("catch a child %d, normal exit status:%d\n", wpid, WEXITSTATUS(status));
}
else if (WIFSIGNALED(status))
{
printf("catch a child %d, kill by signal:%d\n", wpid, WTERMSIG(status));
}
else if (WCOREDUMP(status))
{
printf("catch a child %d, stop status:%d\n", wpid, WIFSTOPPED(status));
}
}
}
int main(int argc, char *argv[])
{
pid_t pid = 0;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGCHLD);
sigprocmask(SIG_BLOCK, &set, NULL);
int ii = 0;
for (ii = 0; ii < 5; ++ii)
{
pid = fork();
if (0 == pid)
{
break;
}
else if (-1 == pid)
{
perror("fork failed");
exit(1);
}
}
if (pid > 0)
{
printf("I'm parent:%d\n", getpid());
struct sigaction act;
act.sa_handler = func;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGCHLD, &act, NULL);
sigprocmask(SIG_UNBLOCK, &set, NULL);
while(1);
}
else if (0 == pid)
{
printf("I'm a child:%d\n", getpid());
return ii;
}
return 0;
}