多线程服务器,信号处理. POSIX [英] Multithreaded server, signal handling. POSIX

查看:166
本文介绍了多线程服务器,信号处理. POSIX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多线程服务器中处理信号处理时遇到麻烦.我为每个连接创建一个线程,但是我想选择使用SIGINT终止服务器.但是,当其中一个线程捕获到信号时,事情变得令人讨厌.除了主线程外,有没有办法阻止线程获取信号?

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?

推荐答案

线程从创建它的线程继承其信号掩码.

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.

要修改线程的信号掩码,POSIX定义 pthread_sigmask() .

To modify a thread's signal mask POSIX defines pthread_sigmask().

更新:

当需要在多线程环境中定期执行信号处理时,一种有趣的方法是将所有信号委托给一个单独的线程,除了使用

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

要这样做:

  1. 使用 在主"线程中优先.
  2. 然后创建线程来处理信号.
  3. 然后使用在主"线程中阻止来自1.的所有信号.再次pthread_sigmask() .
  4. 最后创建所有其他线程.
  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.

结果是,在1.下指定的所有信号都将转到在2.下创建的线程.所有其他线程将不会接收在1.下指定的任何信号.

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

这篇关于多线程服务器,信号处理. POSIX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆