免费注册 查看新帖 |

Chinaunix

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

[Linux] kill能使sem_wait产生EINTR错误,而pthread_kill不能,why? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-03-06 19:27 |只看该作者 |倒序浏览
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4. #include <sys/types.h>
  5. #include <unistd.h>
  6. #include <string.h>
  7. #include <signal.h>
  8. #include <errno.h>

  9. #define PRINTF(fmt, ...)   printf("%s:%d: " fmt, __FUNCTION__, __LINE__, ## __VA_ARGS__)
  10. #define WAIT_INTERVAL      1000

  11. static sem_t sem;

  12. static void sig_handler_drp(int sig)
  13. {
  14.    if (SIGUSR1 == sig)
  15.    {
  16.       PRINTF("SIGUSR1 received\n");
  17.    }
  18. }
  19. void *thread_drp(void *arg)
  20. {
  21.    usleep(WAIT_INTERVAL);
  22.    if (kill(getpid(), SIGUSR1))
  23.    {
  24.       PRINTF("ERROR! kill\n");
  25.    }
  26. //   if (pthread_kill(*(pthread_t *)arg, SIGUSR1))
  27. //   {
  28. //      PRINTF("ERROR! pthread_kill\n");
  29. //   }
  30.    return NULL;
  31. }
  32. int main(int argc, char ** argv)
  33. {
  34.    struct sigaction sa;
  35.    pthread_t tid;

  36.    memset(&sa, 0, sizeof(struct sigaction));
  37.    sa.sa_handler = sig_handler_drp;
  38.    sigemptyset(&sa.sa_mask);
  39.    sa.sa_flags = 0;
  40.    if (-1 == sigaction(SIGUSR1, &sa, NULL))
  41.    {
  42.       PRINTF("ERROR! sigaction\n");
  43.    }
  44.    if (sem_init(&sem, 0, 0))
  45.    {
  46.       PRINTF("ERROR! sem_init\n");
  47.    }
  48.    if (pthread_create(&tid, NULL, thread_drp, &tid))
  49.    {
  50.       PRINTF("ERROR! pthread_create\n");
  51.    }

  52.    if (sem_wait(&sem))
  53.    {
  54.       PRINTF("ERROR! sem_wait\n");
  55.       if (EINTR == errno)
  56.       {
  57.          PRINTF("ERROR! sem_wait gets EINTR\n");
  58.       }
  59.    }

  60.    if (pthread_join(tid, NULL))
  61.    {
  62.       PRINTF("ERROR! pthread_join\n");
  63.    }
  64.    if (sem_destroy(&sem))
  65.    {
  66.       PRINTF("ERROR! sem_destroy\n");
  67.    }

  68.    return 0;
  69. }
复制代码
如上代码,编译后执行输出如下:
sig_handler_drp:19: SIGUSR1 received
main:59: ERROR! sem_wait
main:62: ERROR! sem_wait gets EINTR

如果将kill的代码注释掉,然后pthread_kill的代码打开,则运行后会卡在sem_wait,
为什么pthread_kill不能使使sem_wait产生EINTR错误?

论坛徽章:
1
2015年辞旧岁徽章
日期:2015-03-03 16:54:15
2 [报告]
发表于 2015-03-10 15:39 |只看该作者
你pthread_kill发送给的是thread_drp线程,而sem_wait是在主线程阻塞的,这样主线程不会被打断啊,sem_wait会一直等待的。

论坛徽章:
0
3 [报告]
发表于 2015-03-11 22:38 |只看该作者
本帖最后由 BsiIce 于 2015-03-11 22:42 编辑

回复 2# 羽剑天涯


太感谢了!
原来如此,我发错线程了,我还以为发给线程main了呢,现在我声明个变量tid_self=pthread_self(),然后把pthread_create()的第4个参数改为&tid_self,就OK了。
之前我还以为sig_handler_drp是在线程main中执行的,原来是在thread_drp中执行的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP