首页 > 解决方案 > 为什么Linux信号总是由主线程处理?

问题描述

我使用 pthread_create 来获取 2 个线程并在两个创建的线程中注册信号处理程序。

在主线程中,未设置信号处理程序。

#include <signal.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
void sig_hand(int no)                  //signal handler
{
    printf("handler executing...\n");
    printf("%d\n", pthread_self());
    pthread_exit(NULL);
}

void* thread1(void *arg1)              //thread1
{
    signal(SIGINT, sig_hand);
    printf("%d\n", pthread_self());
}

void * thread2(void * arg2)           //thread2
{
    signal(SIGINT , sig_hand);
    printf("%d\n", pthread_self());
}

int main()
{
    pthread_t t1;
    pthread_t t2;
    sigset_t newmask;
    sigaddset(&newmask, SIGINT);
    // set sigproc, SIGINT can be received; 
    // sigproc not set, SIGINT can't be received
    if(sigprocmask(SIG_BLOCK, &newmask, NULL) < 0){
        perror("sigprocmask error");
    }
    printf("main thread %d\n", pthread_self());
    pthread_create(&t1, NULL, thread1, NULL);
    pthread_create(&t2, NULL, thread2, NULL);
    while(1);
}

如果我不在主线程中设置 sigprocmask,则可以接收 SIGINT,但它由主线程处理,而主线程不注册处理函数。

main thread -1335200000
-1343535360
-1351928064
^Cpthread -1335200000 handler executing...

但是,如果在主线程中设置了 sigprocmask,则当两个子线程已注册处理函数时,将无法接收 SIGINT。


main thread 2061661952
2053326592
2044933888
^C^C

这非常令人困惑。

标签: linuxmultithreadingsignalsposix

解决方案


推荐阅读