进程间通信---命名管道

函数原型:int mkfifo(const char *pathname, mode_t mode);

函数说明:创建一个命名管道,如果成功则返回0,,否则返回-1

 

函数原型:int open(const char *pathname, int flag);

函数说明:一旦已经用mkfifo创建了一个命名管道,就可以用open打开它。返回-1则打开管道失败

 

函数原型:int close(int fd);

函数说明:可以用来关闭一个创建了的管道

 

当打开一个FIFO(命名管道时),非阻塞标志(O_NONBLOCK)产生下列影响:

(1) 在一般情况中(没有说明O_NONBLOCK),只读打开要阻塞到某个其他进程为写打开此FIFO。同理,为写而打开一个FIFO要阻塞到某个其他进程为读而打开它

(2) 如果指定了O_NONBLOCK,则只读打开立即返回。但是,如果没有进程为读而打开一个FOFO,那么只写打开将出错返回,其errnoENXIO

 

  1. //readfifo.cc  
  2. #include <iostream>  
  3. #include <sys/types.h>  
  4. #include <sys/stat.h>  
  5. #include <fcntl.h>  
  6. using namespace std;  
  7.   
  8. const char *fifo_path = "/home/hahaya/Program/进程间通信之命名管道/fifo";  
  9.   
  10. int main()  
  11. {  
  12.     //创建一个命名管道  
  13.     int ret = mkfifo(fifo_path, O_CREAT|0777);  
  14.     if(ret == -1)  
  15.     {  
  16.     cout << "create fifo failed..." << endl;  
  17.     return 0;  
  18.     }  
  19.   
  20.     //打开命名管道  
  21.     int fd = open(fifo_path, O_RDONLY|O_NONBLOCK);  
  22.     if(fd == -1)  
  23.     {  
  24.     cout << "open fifo failed..." << endl;  
  25.     return 0;  
  26.     }  
  27.   
  28.     //从管道中读取数据  
  29.     char buff[128] = {'\0'};  
  30.     while(1)  
  31.     {  
  32.     if(read(fd, buff, sizeof(buff)) > 0)  
  33.     {  
  34.         cout << buff << endl;  
  35.     }  
  36.     }  
  37.   
  38.     //关闭命名管道  
  39.     close(fd);  
  40.     return 0;  
  41. }  
  42.   
  43.   
  44. //writefifo.cc  
  45. #include <iostream>  
  46. #include <sys/types.h>  
  47. #include <sys/stat.h>  
  48. #include <fcntl.h>  
  49. using namespace std;  
  50.   
  51. const char *fifo_path = "/home/hahaya/Program/进程间通信之命名管道/fifo";  
  52.   
  53. int main()  
  54. {  
  55.     //打开命名管道  
  56.     int fd = open(fifo_path, O_WRONLY|O_NONBLOCK, 0);  
  57.     if(fd == -1)  
  58.     {  
  59.     cout << "open fifo failed..." << endl;  
  60.     return 0;  
  61.     }  
  62.   
  63.     //向管道中写入数据  
  64.     char buff[128] = {'\0'};  
  65.     while(1)  
  66.     {  
  67.     cin.getline(buff, sizeof(buff));  
  68.     write(fd, buff, sizeof(buff));  
  69.     }  
  70.   
  71.     close(fd);  
  72.     return 0;  
  73. }  

先运行readfifo程序再运行writefifo,因为命名管道fifo是再readfifo程序中创建的

需要确保fifo_path下没有fifo这个文件,否则在运行readfifo程序时因为命名管道fifo已存在,所以执行mkfifo函数会失败,则会直接退出readfifo程序

writefifo程序下输入的字符,会再readfifo程序下显示


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值