0

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);
    }
}
Wokers
  • 107
  • 3
  • 13

1 Answers1

1

Take a look at this struct sigaction member:

void (*sa_sigaction)(int, siginfo_t *, void *);

Upon handling a signal using sigaction, you can choose to use the basic sa_handler, or you can use sa_sigaction instead, which provides much more details about the signal sending process, including its PID. You can use that to manipulate your program to act upon recieving a signal from a specific process, or in your case, any child process.

Check man sigaction for a complete list of siginfo_t struct fields, you'll be amazed :)

MrBens
  • 1,227
  • 1
  • 9
  • 19