免费注册 查看新帖 |

Chinaunix

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

[C] 多线程的信号问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-09-11 11:09 |只看该作者 |倒序浏览
redhat 2.6中:



  1. int main()
  2. {
  3.     pthread_t pid1;
  4.     pthread_t pid2;

  5.     pthread_create(&pid1,NULL ,thread1_fun,NULL);
  6.     pthread_create(&pid2,NULL,thread2_fun,NULL);

  7.     printf("main thread...\n");
  8.     pause();
  9.     printf("main thread alarm...\n");
  10.     while(1)
  11.         {
  12.          ;
  13.         }

  14.     return 0;
  15. }

  16. void thread1_fun(void)
  17. {
  18.    printf("thread1...\n");
  19.    pause();
  20.    printf("thread1 alarm...\n");
  21. }

  22. void thread2_fun(void)
  23. {
  24.    printf("thread2...\n");
  25.    signal(SIGALARM,alarm_handler);
  26.    alarm(5);
  27.    pause();
  28.    printf("thread2 alarm...\n");
  29. }

  30. void alarm_handler(int sig)
  31. {
  32.     printf("SIGALRM catched...\n");
  33. }

复制代码



为什么总是打印
main thread...
thread1...
thread2...
SIGALRM catched...
mainthread alarm...

怎么不是线程2收到SIGALRM,而是主线程收到呢?把alarm()换成setitimer()也一样

[ 本帖最后由 wliang511 于 2008-9-11 11:31 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2008-09-11 11:24 |只看该作者
对于发送给进程的信号,好像没有标准规定由哪个线程处理,所以由主线程处理也算合理。不过不同的系统实现可能有差别,最好在不同的系统上测试下

论坛徽章:
0
3 [报告]
发表于 2008-09-11 11:25 |只看该作者
我的运行结果是

main thread...
thread1...
thread2...
SIGALRM catched...
thread2 alarm...

论坛徽章:
0
4 [报告]
发表于 2008-09-11 11:32 |只看该作者
原帖由 5毛党党员 于 2008-9-11 11:25 发表
我的运行结果是

main thread...
thread1...
thread2...
SIGALRM catched...
thread2 alarm...


你的是什么环境啊?我的的fedora4,是虚拟机!

论坛徽章:
0
5 [报告]
发表于 2008-09-11 11:36 |只看该作者
linux 2.6.9-22
Red Hat Enterprise Linux AS release 4

论坛徽章:
0
6 [报告]
发表于 2008-09-11 12:55 |只看该作者
原帖由 wliang511 于 2008-9-11 11:09 发表
redhat 2.6中:



int main()
{
    pthread_t pid1;
    pthread_t pid2;

    pthread_create(&pid1,NULL ,thread1_fun,NULL);
    pthread_create(&pid2,NULL,thread2_fun,NULL);

    printf( ...


发送给进程的信号,一般是任意发送给它的线程的,除非是引起硬件故障或自己触发的某些信号。

论坛徽章:
0
7 [报告]
发表于 2008-09-11 13:09 |只看该作者
这是POSIX规定的线程处理信号的原语:
信号到达某个进程,然后再由该进程将信号分发到所有没有阻塞该信号的线程中。

论坛徽章:
0
8 [报告]
发表于 2008-09-11 13:33 |只看该作者
原帖由 cugb_cat 于 2008-9-11 13:09 发表
这是POSIX规定的线程处理信号的原语:
信号到达某个进程,然后再由该进程将信号分发到所有没有阻塞该信号的线程中。


怎么觉得我应该是分发到任意一个没有阻塞该信号的线程中

论坛徽章:
0
9 [报告]
发表于 2008-09-11 15:00 |只看该作者
提示: 作者被禁止或删除 内容自动屏蔽

论坛徽章:
0
10 [报告]
发表于 2008-09-11 15:18 |只看该作者
原帖由 cugb_cat 于 2008-9-11 13:09 发表
这是POSIX规定的线程处理信号的原语:
信号到达某个进程,然后再由该进程将信号分发到所有没有阻塞该信号的线程中。


只会发给一个线程吧
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP