I wrote a simple multithreaded application in C++11
on Linux platform and I would like to terminate the server and its running threads by sending SIGINT
signal.
Obviously my server application uses thread support from C++11 (std::thread
etc.). Although I found some support for signal handling in C++11 (std::signal
), I couldn't find any support for handling signals in multithreaded environment.
So my question is - is there any way how to handle signals in multithreaded application in C++11
or do I have to rely back on pthreads
just because my application needs to deal with signals?
2.4 Signal Concepts:
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.
In the light of the above, in a multi-threaded process a common solution is to block all 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) and is often the main thread. It easy to block the signals in the main thread before creating other threads, that inherit the signal mask of the parent thread. Once the main thread is done creating child threads and is ready to handle signals it must unblock those.
Unfortunately, C++11 does not provide any means for that. You have to use POSIX functions. Scroll down to Signalling in a Multi-Threaded Process in pthread_sigmask for an example that creates a special signal handling thread. The latter is not necessary if you are using an event loop in the main thread that can handle signals, just unblock the signals before entering the event loop.
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