linux下命名管道详解

1. 命名管道

创建命名管道创建方式:

函数:mkfifo(“my.p”,0644)

命令:mkfifo my.p

命名管道作用:在内核中建一块缓冲区,并命名,使得2个没有亲缘关系的进程能够实现通信,通过open这块缓冲区往里面写东西,读东西。一旦这2个进程能够找到了这块共有的缓冲区,可以删除my.p这个文件,删除之后并不影响2个进程的通信。

需要注意的是:当只有进程往这块缓存写东西时(即没有读进程),那么写进程就处于阻塞状态,反之也一样;因此,命名管道必须是2个进程一个写一个读,在Linux下,我们可以使用两个终端来观测。

2. 案例。本案例有3个源文件分别是:(1)创建命名管道(2)写内容到管道里(3)从管道读取东西。

(1)创建命名管道:

  1. 1 #include <stdio.h>  
  2.   2 #include <stdlib.h>  
  3.   3 #include <unistd.h>  
  4.   4   
  5.   5 int main()  
  6.   6 {  
  7.   7     mkfifo("my.p",0644);  
  8.   8     return 0;  
  9.   9 }  

(2)写管道

  1. 1 #include <stdio.h>  
  2.   2 #include <stdlib.h>  
  3.   3 #include <unistd.h>  
  4.   4 #include <fcntl.h>  
  5.   5 int main()  
  6.   6 {  
  7.   7     int fd=open("my.p",O_WRONLY);  
  8.   8     if(fd==-1)  
  9.   9     {  
  10.  10         perror("open failure");  
  11.  11         exit(1);  
  12.  12     }  
  13.  13   
  14.  14     int i=0;  
  15.  15     while(1)  
  16.  16     {  
  17.  17         write(fd,&i,sizeof(i));  
  18.  18         printf("write %d is ok\n",i);  
  19.  19         i++;  
  20.  20         sleep(1);  
  21.  21     }  
  22.  22     return 0;  
  23.  23 }  

(3)读管道

  1. 2 #include <stdio.h>  
  2.  3 #include <stdlib.h>  
  3.  4 #include <unistd.h>  
  4.  5 #include <fcntl.h>  
  5.  6   
  6.  7 int main()  
  7.  8 {  
  8.  9     int fd=open("my.p",O_RDONLY);  
  9. 10     if(fd==-1)  
  10. 11     {  
  11. 12         perror("open failure");  
  12. 13         exit(1);  
  13. 14     }  
  14. 15   
  15. 16     int i=0;  
  16. 17     while(1)  
  17. 18     {  
  18. 19         read(fd,&i,sizeof(i));  
  19. 20         printf("%d\n",i);  
  20. 21         sleep(1);  
  21. 22     }  
  22. 23     return 0;  
  23. 24 }  

另外,关于匿名管道是用于有亲缘关系的管道实现通信的,用pipe()创建,具体见下一篇博客。

猜你喜欢

转载自blog.csdn.net/zy20150613/article/details/80055184