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:
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.