简体   繁体   中英

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. 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. Here's one.

... and the question is: how can I catch SIGTERM in the main program, but make the threads "deaf" to that signal? I guess .

The pthread_sigmask function can be used to allow/deny particular signals to be/from being delivered to the thread. Not all signals can be blocked this way, but SIGTERM can. To construct the required sigset_t object you can use sigemptyset and sigaddset functions. You can see the manpage or click here: 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").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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