Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SIGCHLD handler in c - unwanted wait

Tags:

c

signals

sigchld

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?

like image 819
Shai Avatar asked Dec 14 '25 11:12

Shai


1 Answers

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.

like image 158
iabdalkader Avatar answered Dec 16 '25 03:12

iabdalkader



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!