免费注册 查看新帖 |

Chinaunix

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

[Linux] 如果写到管道时读进程已终止会产生SIGPIPE---怎么实现? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-01-16 14:36 |只看该作者 |倒序浏览
我在学习SIGPIPE时,按照描述就是:如果写到管道时读进程已终止会产生SIGPIPE。另外还有一个socket也会出这个信号,不过socket这个先不管了。我学习FIFO,就想实现“如果写到管道时读进程已终止会产生SIGPIPE”(注:APUE上写的)。
我实现代码如下:
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <errno.h>
  4. #include <fcntl.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <signal.h>
  9. #include <unistd.h>

  10. #define FIFO_SERVER "/tmp/myfifo"

  11. void my_func(int sign_no)
  12. {
  13.         if(sign_no == SIGPIPE)
  14.         {
  15.                 printf("Sorry Sir,I have get SIGPIPE\n");
  16.         }
  17.     else
  18.         exit(1);
  19. }

  20. int main(int argc, char** argv)
  21. {
  22.         int fd;
  23.         char w_buf[100];
  24.         int nwrite;
  25.        
  26.         signal(SIGPIPE, my_func);
  27.        
  28.         if((mkfifo(FIFO_SERVER, O_CREAT|O_EXCL|O_RDWR)<0) && (errno!=EEXIST))
  29.     {
  30.                 printf("Cant create fifioserver\n");
  31.         }       
  32.    
  33.     //fd = creat(FIFO_SERVER,O_RDWR|O_NONBLOCK);
  34.         fd = open(FIFO_SERVER, O_RDWR|O_NONBLOCK, 0);
  35.         if(fd == -1)
  36.         {
  37.                 perror("open");
  38.                 exit(1);
  39.         }
  40.        
  41.        
  42.         if(argc == 1)
  43.         {
  44.                 printf("Please send something\n");
  45.                 exit(-1);
  46.         }
  47.         strcpy(w_buf, argv[1]);
  48.     while(1)
  49.     {
  50.         
  51.         nwrite = write(fd, w_buf, 100);       
  52.             if(nwrite == -1)
  53.             {
  54.                     if(errno == EAGAIN)
  55.                             printf("The FIFO has not been read yet,Please try later\n");
  56.             }
  57.             else
  58.             {
  59.                     printf("Write %s to the FIFO\n", w_buf);
  60.             }
  61.         sleep(1);
  62.     }
  63.         close(fd);
  64.         return 0;
  65. }
复制代码
然后在另一个终端手动删掉/tmp/myfifo这个管道,但是却不行,没有出现SIGPIPE这个信号,谁能帮帮我呀。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP