Chinaunix首页 | 论坛 | 博客
  • 博客访问: 83915
  • 博文数量: 18
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 118
  • 用 户 组: 普通用户
  • 注册时间: 2017-03-25 16:28
个人简介

***

文章分类

全部博文(18)

文章存档

2017年(18)

我的朋友

分类: C/C++

2017-08-14 09:43:14

引用-http://blog.csdn.net/u014285517/article/details/50479504

命名管道
的读写有阻塞和非阻塞两种,可以在open()时指定,下面我们对各种情况进行一些讨论。

点击(此处)折叠或打开

  1. //写进程
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <string.h>
  7. #include <stdio.h>
  8. #define FIFO_NAME "/tmp/myfifo"
  9. main()
  10. {
  11.     int fd;
  12.     char w_buf[50];
  13.     int w_num;

  14.     // 若fifo已存在,则直接使用,否则创建它
  15.     if((mkfifo(FIFO_NAME,0777)<0)&&(errno!=EEXIST))
  16.     {
  17.         printf("cannot create fifo...\n");
  18.         exit(1);
  19.     }

  20.     //以阻塞型只写方式打开fifo
  21.     fd=open(FIFO_NAME,O_WRONLY);
  22.     w_num=write(fd,"abcdg\0",6);
  23.     printf("%d\n",w_num);
  24. }


点击(此处)折叠或打开

  1. //读进程
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #define FIFO_NAME "/tmp/myfifo"
  7. main()
  8. {
  9.     char r_buf[50];
  10.     int fd;
  11.     int r_num;

  12. // 若fifo已存在,则直接使用,否则创建它
  13.     if((mkfifo(FIFO_NAME,0777)<0)&&(errno!=EEXIST))
  14.     {
  15.         printf("cannot create fifo...\n");
  16.         exit(1);
  17.     }
  18.     //以阻塞型只读方式打开fifo
  19.     fd=open(FIFO_NAME,O_RDONLY);
  20.     if(fd==-1)
  21.     {
  22.         printf("open %s for read error\n");
  23.         exit(1);
  24.     }

  25.     // 通过键盘输入字符串,再将其写入fifo,直到输入"exit"为止
  26.     r_num=read(fd,r_buf,6);
  27.     printf(" %d bytes read:%s\n",r_num,r_buf);

  28.     unlink(FIFO_NAME);//删除fifo
  29. }


阅读(4121) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~