Search code examples
multithreadingpthreadssignalsposix

Multithreaded server, signal handling. POSIX


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?


Solution

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

    1. Set the signal mask as per the signals you want to handle using pthread_sigmask() in the "main" thread prior to anything else.
    2. Then create the thread to handle the signals.
    3. Then block all signals from 1. in the "main" thread by using pthread_sigmask() again.
    4. 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..