Determine the pid of the completed process

I am trying to understand that pid is the process that sent the SIGCHLD signal, and I want to do this in the signal handler that I created for SIGCHLD. How can I do it? I'm trying to:

int pid = waitpid(-1, NULL, WNOHANG);

because I want to wait for any child process that is spawned.

+5
source share
1 answer

If you use waitpid()more or less, as shown, you will be given the PID of one of the child processes that died - usually this will be the only process that died, but if you get a flurry of them, you can get one signal and many corpses to collect. So use:

void sigchld_handler(int signum)
{
    pid_t pid;
    int   status;
    while ((pid = waitpid(-1, &status, WNOHANG)) != -1)
    {
        unregister_child(pid, status);   // Or whatever you need to do with the PID
    }
}

&status NULL, .

+7

All Articles