Multithreaded server, signal handling. POSIX

可紊 提交于 2019-12-10 23:35:47

问题


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?


回答1:


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




回答2:


pthread_sigmask() is exactly what you need. Allow SIGINT processing only in a thread that is supposed to catch this signal.



来源:https://stackoverflow.com/questions/20728773/multithreaded-server-signal-handling-posix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!