评论后编辑的问题"Oh sry it worked :D"
。这很尴尬,但我应该说pthread_sigmask
代码的版本也不起作用。这是pthread_sigmask
代码的版本及其在SIGCHLD
解锁之前收到的输出!
void signalHandler(int signal_number) {
if ((debug & 1) == 1) {
cout << "\n" << getTime() << " signal handler: process " << getpid() << " received signal " << signal_number << "\n";
}
}
void * test(void*){
sigset_t chldmask;
if ((sigemptyset(&chldmask) == -1) || (sigaddset(&chldmask, SIGCHLD) == -1)) {
perror("Failed to initialize the signal mask");
return NULL;
}
if (pthread_sigmask(SIG_BLOCK, &chldmask, NULL) == -1) {
return NULL;
}
fprintf(stderr, "SIGCHLD signal blocked\n");
int child = fork();
if (child == 0) {
cout << "\nI'm child " << getpid() << " exiting now.\n";
fflush(stdout);
exit();
}
cout << "\nI'm parent " << getpid() << " not yet exiting.\n";
cout << "\ngonna sleep for 10 secs\n";
sleep(10);
cout << "\nunblocking SIGCHLD after 10 secs\n";
if (pthread_sigmask(SIG_UNBLOCK, &chldmask, NULL) == -1) {
return NULL;
}
cout << "\nExiting the thread!\n";
fflush(stdout);
}
int main(){
struct sigaction signalaction_struct;
memset(&signalaction_struct, 0, sizeof (signalaction_struct));
signalaction_struct.sa_handler = &signalHandler;
sigaction(SIGCHLD, &signalaction_struct, NULL);
sigaction(SIGUSR1, &signalaction_struct, NULL);
sigaction(SIGUSR2, &signalaction_struct, NULL);
pthread_t test_thread;
pthread_create(&test_thread,NULL,&test,NULL);
pthread_join(test_thread,NULL);
return 0;
}
输出:
SIGCHLD 信号被阻塞
我是父母 13177 尚未退出。
睡10秒
我是孩子 13182 现在退出。
2013-11-06 19:47:36 信号处理程序:进程 13177 收到信号 17
10 秒后解除阻塞 SIGCHLD
退出线程!
如何阻止来自线程的信号?我必须保护线程中的一段代码免受SIGCHLD
. 似乎在多线程程序中处理异步信号回答了我的问题,但我不知道如何安排事情。我正在寻找一些建议和解释。谢谢你。