多线程中处理信号的线程是哪一个

  进程收到信号会被处理,但是处理信号的线程是哪一个呢?主线程,注册信号函数的线程,还是任意的子线程。

结论:

  哪个线程收到的信号,信号处理函数就在哪个线程上面执行,和信号函数是哪个线程注册的无关。如果是其它进程发给当前进程的,那就都是在主线程处理。

测试代码:

  1、创建两个子线程,子线程1注册信号函数

  2、主线程定时向子线程发信号

  3、在shell终端中手动给程序法信号(ctrl+c)

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<signal.h>

void sighandler(int signo)
{
        printf("sighandler thread id=%lu\n",pthread_self());//获取当前线程ID
    printf("signal = [%d]\n", signo);
}

void* thread_func1(void* arg) {

        signal(SIGINT, sighandler);    //子线程注册信号函数

        printf("thread_func1 thread id=%lu\n",pthread_self());//获取当前线程ID
        while(1);
}

void* thread_func2(void* arg) {
        printf("thread_func2 thread id=%lu\n",pthread_self());//获取当前线程ID
        while(1);
}

int main() {
    pthread_t tid1, tid2;

        //signal(SIGINT, sighandler);    //主线程注册信号函数

        printf("main thread id=%lu\n",pthread_self());//获取当前线程ID
    if (pthread_create(&tid1, NULL, (void*)thread_func1, "new thread:") != 0) {
        printf("pthread_create error.");
        exit(EXIT_FAILURE);
    }

    if (pthread_create(&tid2, NULL, (void*)thread_func2, "new thread:") != 0) {
        printf("pthread_create error.");
        exit(EXIT_FAILURE);
    }

        while(1){
                sleep(1);
                pthread_kill(tid2, SIGINT);
        }

    return 0;
}

 

测试结果:

  

 

posted @ 2022-03-29 20:47  核心已转储  阅读(523)  评论(0)    收藏  举报