简体   繁体   English

Linux处理多线程程序中特定线程上的信号

[英]Linux handling a signal on a specific thread in a multi-threaded program

I have a program that I want to accept and handle incoming TCP connections until it gets a terminate signal. 我有一个程序要接受并处理传入的TCP连接,直到它收到终止信号。 There are additional threads doing data processing that I don't have full control over but am able to cleanly stop/abort if I want the program to exit. 还有其他线程在执行数据处理,我无法完全控制这些线程,但是如果我要退出程序,则可以干净地停止/中止线程。

while (true)
{
    select(...)?
    if (got-terminate-signal)
    {
        break;
    }
    else
    {
        ...do stuff with sockets based on select...
    }
}

Your question isn't very clear, but I'll take a stab at what I think you're getting at. 您的问题不是很清楚,但是我会刺探您的想法

Signals are like interrupts, and the routine that catches them are like interrupt service routines (the analogy may or may not be perfect). 信号就像中断,捕获它们的例程就像中断服务例程(类比可能完美也可能不完美)。 You'd probably note the fact that the signal happened within the handler, then signal another thread via a synchronization method of some kind (semaphore, for example). 您可能会注意到以下事实:信号发生在处理程序内,然后通过某种同步方法(例如信号量)向另一个线程发出信号。

Doing a quick Google search turns up many pages on the subject. 快速进行Google搜索会打开与此主题相关的许多页面。 Here's one. 这是一个

... and the question is: how can I catch SIGTERM in the main program, but make the threads "deaf" to that signal? ...问题是:如何在主程序中捕获SIGTERM,但使该信号“聋”起来? I guess . 我猜

The pthread_sigmask function can be used to allow/deny particular signals to be/from being delivered to the thread. pthread_sigmask函数可用于允许/拒绝将特定信号传递到线程或从中传递到线程。 Not all signals can be blocked this way, but SIGTERM can. 并非所有信号都可以这种方式被阻止,但是SIGTERM可以。 To construct the required sigset_t object you can use sigemptyset and sigaddset functions. 要构造所需的sigset_t对象,可以使用sigemptysetsigaddset函数。 You can see the manpage or click here: http://cursuri.cs.pub.ro/~apc/2003/resources/pthreads/uguide/users-96.htm 您可以查看手册页或单击此处: http : //cursuri.cs.pub.ro/~apc/2003/resources/pthreads/uguide/users-96.htm

Note that this function works on "current thread" so it should be called as the first thing that the thread-callback-function does (not "before running the thread"). 请注意,此函数在“当前线程”上起作用,因此应首先将其称为线程回调函数(而不是“在运行线程之前”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM