linux C ++无法阻塞来自线程的信号

时间:2013-11-06 11:34:21

标签: c++ linux multithreading

在评论"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的线程中的一段代码。似乎Dealing With Asynchronous Signals In Multi Threaded Program回答了我的问题,但我没有得到如何安排的事情。我正在寻找一些建议和解释。谢谢。

0 个答案:

没有答案