Chinaunix首页 | 论坛 | 博客
  • 博客访问: 396442
  • 博文数量: 75
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 645
  • 用 户 组: 普通用户
  • 注册时间: 2015-06-03 18:24
文章分类

全部博文(75)

文章存档

2019年(1)

2018年(20)

2017年(14)

2016年(10)

2015年(30)

分类: LINUX

2015-06-28 23:35:31

上一篇博文主要介绍了进程间通信之无名管道,那可想而知接下来就该介绍有名管道了。

FIFO也被称为有名管道,无名管道只能在有亲缘关系的两个进程间进行通信,但是有名管道可以在非亲缘关系的两个进程间进行通信。

1、
相关函数介绍

Mkfifo函数就是创建一个fifo文件,用来进行管道传输。
2、有名管道的一些特征

①如果mkfifo的第一个参数是一个已经存在路径名时,会返回EEXIST错误,所以一般典型的调用代码首先会检查是否返回该错误,如果确实返回该错误,那么只要调用打开FIFO的函数就可以了。


②当以只读方式打开一个fifo文件时,open函数会阻塞直到有进程以只写方式打开该fifo文件。


③当以只写方式打开一个fifo文件时,open函数会阻塞直到有进程以只读方式打开该fifo文件。

3、程序例子


写进程

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<errno.h>

  4. #include<sys/types.h>
  5. #include<sys/stat.h>
  6. #include<fcntl.h>


  7. int main(int argc,char **argv)
  8. {
  9.     int fd;
  10.     if(argc < 2)
  11.     {
  12.         printf("usage:%s pathname\n",argv[0]);
  13.         exit(0);
  14.     }

  15.     if(mkfifo(argv[1],0666) < 0 && errno != EEXIST)
  16.     {
  17.         perror("fail to mkfifo");
  18.         exit(1);
  19.     }

  20.     if((fd = open(argv[1],O_WRONLY/*|O_NONBLOCK*/)) < 0)
  21.     {
  22.         perror("fail to open");
  23.         exit(1);
  24.     }

  25.     printf("open for write success\n");

  26.     int n;
  27.     char buf[10] = {"123456789"};
  28.     
  29.     while(1)
  30.     {
  31.         printf("\n>");
  32.         scanf("%d",&n);

  33.         int write_sum;
  34.         write_sum = write(fd,buf,n);
  35.         printf("%d bytes writed\n",write_sum);
  36.     }

  37.     return 0;
  38. }

读进程


点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<errno.h>

  4. #include<sys/types.h>
  5. #include<sys/stat.h>
  6. #include<fcntl.h>

  7. #include<strings.h>


  8. int main(int argc,char **argv)
  9. {
  10.     if(argc < 2)
  11.     {
  12.         printf("usage:%s pathname\n",argv[0]);
  13.         exit(1);
  14.     }

  15.     int fd;

  16.     if(mkfifo(argv[1],0666) < 0 && errno != EEXIST)
  17.     {
  18.         printf("fail to mkfifo");
  19.         exit(1);
  20.     }

  21.     if((fd = open(argv[1],O_RDONLY)) < 0)
  22.     {
  23.         perror("fail to open");
  24.     }

  25.     printf("open fifo for read success\n");

  26.     int n;
  27.     char buf[100];
  28.     while(1)
  29.     {
  30.         bzero(buf,sizeof(buf));
  31.         printf("\n>");
  32.         scanf("%d",&n);
  33.         int read_sum;
  34.         read_sum = read(fd,buf,n);
  35.         printf("read_sum=%d,buf:%s\n",read_sum,buf);
  36.     }


引用:http://blog.chinaunix.net/uid-26833883-id-3227144.html

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