I have a parent process spawning several child processes. I want to know when any child process exits by registering a SIGCHLD
signal handler.
The question is, what happens if another SIGCHLD
(or any other signal) is received, while the parent process is already in a signal handler?
I can think of the following outcomes:
Which one is correct?
If a child process receives a signal, a waiting parent will then continue execution leaving an orphan process behind. Hence it is sometimes needed to check the argument set by wait, waitpid or waitid and, in the case that WIFSIGNALED is true, wait for the child process again to deallocate resources.
If a signal arrives which the program has neither handled nor ignored, its default action takes place. Each kind of signal has its own default action, documented below (see Standard Signals). For most kinds of signals, the default action is to terminate the process.
A new process is created with fork. The parent process returns to the main function and wait for a new input from the user. The child process executes in the background. The child process ends and SIGCHLD is triggered.
A signal handler is a function which is called by the target environment when the corresponding signal occurs. The target environment suspends execution of the program until the signal handler returns or calls longjmp() . Signal handlers can be set with signal() or sigaction() .
In your concrete example (the same signal being received), the signal is delivered after the signal handler has finished (so bullet point #2 is correct). Note, however, that you may "lose" signals.
The reason for that is that while a signal is being inside its handler, it is blocked. Blocked signals are set to pending, but not queued. The term "pending" means that the operating system remembers that there is a signal waiting to be delivered at the next opportunity, and "not queued" means that it does this by setting a flag somewhere, but not by keeping an exact record of how many signals have arrived.
Thus, you may receive 2 or 3 (or 10) more SIGCHLD
while in your handler, but only see one (so in some cases, bullet point #1 can be correct, too).
Note that several flags that you can pass to sigaction
can affect the default behaviour, such as SA_NODEFER
(prevents blocking signal) and SA_NOCLDWAIT
(may not generate signal at all on some systems).
Now of course, if you receive a different type of signal, there's no guarantee that it won't interrupt your handler. For that reason, one preferrably doesn't use non signal safe functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With