I have 1 Parent and 4 child processes. I want to catch SIGCHILD from every child and call waitid() for every child.
The question is that how can I know SIGCHILD comes from which process?
And additional question, if I call wait(NULL) in handler, is it called for the child who sent SIGCHILD? Here is the code,
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);
}
}