我有 1 个父进程和 4 个子进程。我想从每个孩子那里捕获 SIGCHILD 并为每个孩子调用 waitid() 。
问题是我怎么知道 SIGCHILD 来自哪个进程?
还有一个问题,如果我在处理程序中调用 wait(NULL),是否会为发送 SIGCHILD 的孩子调用?这是代码,
int main()
{
int pid1, pid2, pid3, pid4;
pid1 = fork();
// parent
if(pid1 > 0)
{
pid2 = fork();
// parent
if(pid2 > 0)
{
pid3 = fork();
//parent
if(pid3 > 0)
{
pid4 = fork();
//child 4
if(pid4 == 0)
{
printf("4. child id: %d, parent %d\n", getpid(), getppid());
exit(1);
}
}
// child 3
if(pid3 == 0)
{
printf("3. child id: %d, parent %d\n", getpid(), getppid());
exit(1);
}
}
// child 1
if(pid2 == 0)
{
printf("1. child id: %d, parent %d\n", getpid(), getppid());
exit(1);
}
struct sigaction sigchld_action;
memset(&sigchld_action, 0, sizeof(sigchld_action));
sigchld_action.sa_handler = &clean_up;
sigaction(SIGCHLD, &sigchld_action, NULL);
//sleep(2);
printf("waiting for children ..\n");
//sleep(2);
printf("they all gone, im closing too ..");
}
// child 2
else if(pid1 == 0)
{
printf("2. child id: %d, parent %d\n", getpid(), getppid());
exit(1);
}
}