Chinaunix首页 | 论坛 | 博客
  • 博客访问: 269717
  • 博文数量: 113
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1044
  • 用 户 组: 普通用户
  • 注册时间: 2015-02-15 16:09
文章分类

全部博文(113)

文章存档

2016年(5)

2015年(108)

我的朋友

分类: C/C++

2015-09-17 23:02:41


点击(此处)折叠或打开

  1. Linux 进程间通讯之有名管道方式
  2. 有名管道mkfifo:

  3. int mkfifo(const char *pathname, mode_t mode)

  4. pathname: FIFO文件名

  5. mode: 属性

  6. 一旦创建了了FIFO,就可open去打开它,可以使用open,read,close等去操作FIFO

  7. 当打开FIFO时,非阻塞标志(O_NONBLOCK)将会对读写产生如下影响:

  8. 1、没有使用O_NONBLOCK:访问要求无法满足时进程将阻塞。如试图读取空的FIFO,将导致进程阻塞;

  9. 2、使用O_NONBLOCK:访问要求无法满足时不阻塞,立即出错返回,errno是ENXIO;

  10. 示例:

  11. 读管道example:

  12. #include <stdio.h>

  13. #include <sys/stat.h>

  14. #include <fcntl.h>

  15. #include <unistd.h>

  16. #include <string.h>

  17. #include <stdlib.h>

  18. #define P_FIFO "/tmp/p_fifo"

  19. int main(int argc, char** argv){

  20.          charcache[100];

  21.          intfd;

  22.          memset(cache,0, sizeof(cache)); //初始化内存

  23.          if(access(P_FIFO,F_OK)==0){ //管道文件存在

  24.                    execlp("rm","-f", P_FIFO, NULL); //删掉

  25.                    printf("access.\n");

  26.          }

  27.          if(mkfifo(P_FIFO, 0777) < 0){

  28.                    printf("createnamed pipe failed.\n");

  29.          }

  30.          fd= open(P_FIFO,O_RDONLY|O_NONBLOCK); // 非阻塞方式打开,只读

  31.          while(1){ // 一直去读

  32.                    memset(cache,0, sizeof(cache));

  33.                    if((read(fd,cache, 100)) == 0 ){ // 没有读到数据

  34.                             printf("nodata:\n");

  35.                    }

  36.                    else

  37.                             printf("getdata:%s\n", cache); // 读到数据,将其打印

  38.                             sleep(1); //休眠1s

  39.          }

  40.          close(fd);

  41.          return0;

  42. }

  43. 写管道example:

  44. #include <stdio.h>

  45. #include <fcntl.h>

  46. #include <unistd.h>

  47. #define P_FIFO "/tmp/p_fifo"

  48. int main(int argc, char argv[]){

  49.          intfd;

  50.          if(argc< 2){

  51.                    printf("pleaseinput the write data.\n");

  52.          }

  53.          fd= open(P_FIFO,O_WRONLY|O_NONBLOCK); //非阻塞方式

  54.          write(fd,argv[1], 100); //将argv[1]写道fd里面去

  55.          close(fd);

  56. }

测试:

root--> ./mkfifo_r
no data:
no data:
get data:linuxdba
no data:
no data:
no data:
no data:
no data:

......

root--> ./mkfifo_w linuxdba
root-->


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