我有一个基本的问题,处理信号在多线程过程。mutlti-threaded过程中的信号处理
在我的代码,我创建从主线程一个子线程,听一个SIGALRM
这将是由主线程后触发(使用其他功能一样timer_create
给了我同样的结果,所以请不要关注在此)。
问题是,而不是捕捉信号,整个过程终止与控制台上一个奇怪的“闹钟”输出。
这是我的代码:
#include <iostream>
#include <sys/time.h>
#include <unistd.h>
#include <csignal>
using namespace std;
void* run_something(void* args){
//unblock the SIGALRM to be catched
sigset_t sig;
sigemptyset(&sig);
sigaddset(&sig, SIGALRM);
sigprocmask(SIG_UNBLOCK, &sig, NULL); //tried with pthread_sigmask
//wait for SIGALRM
int catchedSig;
sigwait(&sig, &catchedSig);
cout<<"in sub-thread, SIGALRM catched, return"<<endl;
}
int main(int argc, char** argv){
//block SIGALRM in main thread
sigset_t sig;
sigemptyset(&sig);
sigaddset(&sig, SIGALRM);
sigprocmask(SIG_BLOCK, &sig, NULL);
//create new thread
pthread_t thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&thread, &attr, run_something, NULL);
//trigger SIGARLM after 2s
alarm(2); //tried with timer_create/sigevent
//wait
cout<<"in main thread, waiting for sub-thread to terminate"<<endl;
pthread_join(thread, NULL);
cout<<"in main thread, terminating"<<endl;
return EXIT_SUCCESS;
}
预期结果
- 在主线程,等待子线程终止子线程
- ,
SIGALRM
被抓到,回报 - 主线程中,终止
把观察结果
-
在主线程
- ,等待子线程终止
- 闹钟
附加信息: 我用G ++(Debian的5.4 .0-4)5.4.0 20160609.
我怀疑这个问题的C++行为与C实现的不同。 @CherubimAnand – alk
@CherubimAnand:我认为我会对搜索同一事物的人有用C – Immort