I am trying to terminate correctly my multi-threaded C++11 application upon receiving SIGINT signal (^C
it is), but for some reason it does not propagate to child t
I am trying to terminate correctly my multi-threaded C++11 application upon receiving SIGINT signal (^C it is), but for some reason it does not propagate to child threads, though main thread responds to it well.
POSIX distinguishes signals targeted to process or a thread. In either case only one thread receives the signal:
At the time of generation, a determination shall be made whether the signal has been generated for the process or for a specific thread within the process. Signals which are generated by some action attributable to a particular thread, such as a hardware fault, shall be generated for the thread that caused the signal to be generated. Signals that are generated in association with a process ID or process group ID or an asynchronous event, such as terminal activity, shall be generated for the process.
...
... Signals generated for the process shall be delivered to exactly one of those threads within the process which is in a call to a sigwait() function selecting that signal or has not blocked delivery of the signal. If there are no threads in a call to a sigwait() function selecting that signal, and if all threads within the process block delivery of the signal, the signal shall remain pending on the process until a thread calls a sigwait() function selecting that signal, a thread unblocks delivery of the signal, or the action associated with the signal is set to ignore the signal.
In a multi-threaded process a common solution is to block process signals one intends to handle in all threads but one. That one thread would normally handle all process signals and tell other threads what to do (e.g. terminate).
Also, because signaled
is set by the signal handler, it should be declared volatile
, this is one of the two use cases volatile
was introduced for:
static int volatile signaled = 0;