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

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

结论:

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

测试代码:

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#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 @   核心已转储  阅读(456)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示