linux - 为什么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
这非常令人困惑。
解决方案
推荐阅读
- node.js - 如何正确允许使用 MongoDB Realm 进行匿名身份验证?
- php - 问:如何在 Laravel 中按用户名显示、更新、编辑用户资料?
- python - 我如何从 postgresql 数据库表中读取图像并在 django 的 face_recognition 函数中使用它
- google-apps-script - 谷歌表格脚本富文本生成器输出
- android - React Native ActivityIndicator 不显示
- bash - 在 cygwin 终端中将文件的内容直接放入剪贴板
- physics - 模拟一系列具有各种质量和耦合函数的旋转顶点
- c# - 有没有办法在 lambda 表达式的 where 条件中使用 forEach?
- c++ - C++ STD::List:遍历列表时遇到问题
- rust - 如何为外国类型生成我的特征的实现?