在Linux中使用多个线程进行信号处理

时间:2012-07-26 23:36:50

标签: c linux multithreading signals ipc

在Linux中,当程序(可能有多个线程)收到SIGTERM或SIGHUP等信号时会发生什么?

哪个线程拦截信号?多个线程可以获得相同的信号吗?是否有专门用于处理信号的特殊线程?如果没有,那么处理信号的线程内部会发生什么?信号处理程序例程完成后如何恢复执行?

2 个答案:

答案 0 :(得分:122)

pthreads(7)描述了POSIX.1要求进程共享属性中的所有线程,包括:

  • 信号处理

POSIX.1还要求每个线程都有一些 distinct 属性,包括:

Linux内核的complete_signal例程具有以下代码块 - 注释非常有用:

/*
 * Now find a thread we can wake up to take the signal off the queue.
 *
 * If the main thread wants the signal, it gets first crack.
 * Probably the least surprising to the average bear.
 */
if (wants_signal(sig, p))
        t = p;
else if (!group || thread_group_empty(p))
        /*
         * There is just one thread and it does not need to be woken.
         * It will dequeue unblocked signals before it runs again.
         */
        return;
else {
        /*
         * Otherwise try to find a suitable thread.
         */
        t = signal->curr_target;
        while (!wants_signal(sig, t)) {
                t = next_thread(t);
                if (t == signal->curr_target)
                        /*
                         * No thread needs to be woken.
                         * Any eligible threads will see
                         * the signal in the queue soon.
                         */
                        return;
        }
        signal->curr_target = t;
}

/*
 * Found a killable thread.  If the signal will be fatal,
 * then start taking the whole group down immediately.
 */
if (sig_fatal(p, sig) &&
    !(signal->flags & SIGNAL_GROUP_EXIT) &&
    !sigismember(&t->real_blocked, sig) &&
    (sig == SIGKILL || !p->ptrace)) {
        /*
         * This signal will be fatal to the whole group.
         */

因此,您会看到负责信号传递的位置:

如果您的进程已将信号的处置设置为SIG_IGNSIG_DFL,则会忽略所有线程的信号(或默认值 - kill,core或ignore)。

如果您的进程已将信号的处置设置为特定处理程序例程,则可以通过使用pthread_sigmask(3)操纵特定线程信号掩码来控制哪个线程将接收信号。您可以指定一个线程来管理它们,或者为每个信号创建一个线程,或者为特定信号创建这些选项的任何混合,或者您依赖于Linux内核当前将信号传递到主线程的默认行为。

然而,根据signal(7)手册页,有些信号是特殊的:

  

可以为整个过程生成(并因此待决)信号   (例如,使用kill(2)发送时)或特定线程(例如,   某些信号,如SIGSEGV和SIGFPE,生成为   执行特定机器语言指令的结果是   线程定向,以及针对特定线程使用的信号   pthread_kill(3))。可以将过程引导的信号传递给任何信号   其中一个当前没有阻塞信号的线程。   如果多个线程的信号未被阻塞,那么   内核选择一个任意线程来传递信号。

答案 1 :(得分:34)

根据您使用的Linux内核版本,这有点细微差别。

假设2.6 posix线程,并且如果您正在讨论发送SIGTERM或SIGHUP的OS,则将信号发送到进程,该进程由根线程接收并由其处理。使用POSIX线程,您也可以将SIGTERM发送到各个线程,但我怀疑您是在询问操​​作系统将信号发送到进程时会发生什么。

在2.6中,SIGTERM将导致子线程“干净地”退出,而在2.4中,子线程处于不确定状态。

相关问题