免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1651 | 回复: 2
打印 上一主题 下一主题

"快速“运行的线程为什么不能catch signal [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-03-07 10:37 |只看该作者 |倒序浏览
我正在写一个多线程程序,需要处理signal。我采取了两种方式。

1)除main thread外,其它线程屏蔽所有signal。main thead通过sigaction()注册signal_handler函数处理信号。
2)对所有线程屏蔽所有signal。开启一个单独线程,通过sigwait()同步等待信号,并处理。

如果我在main thread中加入sleep调用“放缓”运行,通过kill发送信号都能收到并处理。但如果去掉sleep使main thread“快速”运行,发n次信号都不能被收到。

有谁知道为什么么?

论坛徽章:
11
技术图书徽章
日期:2014-03-01 14:44:34天蝎座
日期:2014-05-21 22:11:59金牛座
日期:2014-05-30 17:06:14
2 [报告]
发表于 2012-03-07 10:57 |只看该作者
这么具体的问题,没代码,鬼才知道啊

论坛徽章:
0
3 [报告]
发表于 2012-03-07 11:05 |只看该作者
本帖最后由 rocklinux 于 2012-03-07 11:15 编辑

回复 2# timespace

1)  这是第一种方案,main thread注册signal handler处理信号
     sigset_t newmask, saved_mask;

     sigfillset(&newmask);
     sigdelset(&newmas, SIGINT);
     if (pthread_sigmask(SIG_SETMASK, &newmask, &saved_mask) < 0)
                return ERR_FAIL;

        struct sigaction act, saved_act;
        act.sa_handler = s_sig_handler_func;
        sigemptyset(&act.sa_mask);
        act.sa_flags = 0;

        if (sigaction(SIGINT, &act, &saved_act) < 0)
           return ERR_FAIL;

2)这是第二种方案,开启一个独立线程,专门处理signal

// in main thread
ret = pthread_create(&m_sig_handler_thread, NULL, s_sig_handler_thread_func, NULL);

// a dedicated thread
void *s_sig_handler_thread_func(void *)
{
        int rc = 0;
    sigset_t waitset;

    sigemptyset(&waitset);
    sigaddset(&waitset, SIGINT);

    while (1) {
            rc = sigwaitinfo(&waitset, NULL);
            if (rc != SIGINT)
                    continue;
            cout << "Signal handler thread " << pthread_self() << " received a SIGINT." << endl;
            break;
    }
    return NULL;
}

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP