I have trouble dealing with signal handling in my multithreaded server. I create one thread per connection but I want to have an option to terminate the server with SIGINT. However, things get nasty when one of the threads catches the signal. Is there a way I could block the threads from getting the signal except for the main thread?
2 Answers
A thread inherits its signal mask from the thread creating it.
Assuming the creating thread is the "main" thread, you might like to block all signals in question prior to creating a thread and after the code is done with this unblock the signals in the creating thread.
To modify a thread's signal mask POSIX defines pthread_sigmask()
.
Update:
When signal handling needs to be performed on a regular base in a multithreaded environment, an interesting approach is to delegate all signals to a separate thread doing nothing else but waiting for signals to arrive using sigwait()
.
To do so:
- Set the signal mask as per the signals you want to handle using
pthread_sigmask()
in the "main" thread prior to anything else. - Then create the thread to handle the signals.
- Then block all signals from 1. in the "main" thread by using
pthread_sigmask()
again. - And finally create all other threads.
The result would be that all signals specified under 1. would go to the thread created under 2.. All other threads would not receive any of the signals specified under 1..

- 69,737
- 10
- 105
- 255
-
the problem here is that I create a new thread everytime I get a connection therefore by no means can I unblock a signal after creating _all_ the threads – darenn Dec 22 '13 at 11:53
-
Another problem is.. my server is operating in a loop while(running) { msgrcv()... }. When I catch the signal I set running to false but the main thread is still stuck on msgrcv. is there any way i can deal with that except destroying the ipc queue and checking for EIDRM error? – darenn Dec 22 '13 at 14:25
pthread_sigmask() is exactly what you need. Allow SIGINT processing only in a thread that is supposed to catch this signal.

- 4,171
- 1
- 19
- 31
-
This approach introduces a race for the time between the thread's creation and when the thread calls `pthread_sigmask()`. – alk Dec 22 '13 at 11:23
-
@alk yep but this isn't a real problem and is easily worked around in multiple ways. – Netch Dec 22 '13 at 11:28