Question

I've the following problem with the SIGCHLD handler function.

The handler code is pretty simple:

void sigchld_handler(int signum)
{
    pid_t ended;    
    signal(SIGCHLD, sigchld_handler);
    ended = wait(NULL);
    // do some stuff with the PID of the finished child process
}

This works well when I fork only one child. If I have 2 children (or more) and one of them has finished running, the sigchld_handler() starts and when it gets to the "ended = wait(NULL)" line, the program waits until the other child I have finishes.

Is there a way to get the PID of the child that just ended in a different way and avoid this wait?

Was it helpful?

Solution

Use sigaction() instead, the handler will have this signature:

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

And it's passed the information you want in struct siginfo_t, from the man page:

SIGCHLD fills in si_pid, si_uid, si_status, si_utime and si_stime, providing information about the child. The si_pid field is the process ID of the child

Note: you still need to wait() on the child process of course, unless you use SA_NOCLDWAIT.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top