命名管道
1、与管道的区别:提供了一个路径名与之关联,以FIFO文件的形式存储于文件系统中,能够实现任何两个进程之间通信。而匿名管道对于文件系统是不可见的,它仅限于在父子进程之间的通信。2、FIFO是一个设备文件,在文件系统中以文件名的形式存在,因此即使进程与创建FIFO的进程不存在血缘关系也依然可以通信,前提是可以访问该路径。
3、FIFO(first input first output)总是遵循先进先出的原则,即第一个进来的数据会第一个被读走。
相比于匿名管道他可以在无关的两个进程间进行通信,并且他提供了open函数,对弈上一章对匿名管道的介绍,匿名管道并没有提供open函数。
具体在使用上也有区别 首先必须先要创建管道文件。
mkfifo 路径 文件名对于命名管道而言只能是一个读另一个写所以open时他的权限是有所限制。它也属于管道文件系统管理。他并不是真正磁盘上的文件他是一个设备文件。所以一般意义上而言管道都在内存上。
摘抄man手册的一句话
A FIFO special file is similar to a pipe, except that it is created in a different way. Instead of being an anonymous communications channel, a FIFO special file is entered into the file system by calling mkfifo().
- #include <stdio.h>
- 2 #include <stdlib.h>
- 3 #include <fcntl.h>
- 4 #include <string.h>
- 5 #include <assert.h>
- 6 int main()
- 7 {
- 8 int fd=open("fifo",O_RDONLY);
- 9 assert(fd!=-1);
- 10 printf("fd=%d",fd);
- 11 char buff[128]={0};
- 12 gets(buff);
- 13 read(fd,buff,128);
- 14 printf("%s",buff);
- 15 return 0;
- 16 }
- ~
- ~ 命名管道的用法(两个进程间的通信)通过管道文件
- ~ #include <stdlib.h>
- 3 #include <fcntl.h>
- 4 #include <string.h>
- 5 #include <assert.h>
- 6 int main()
- 7 {
- 8 char buff[128]={0};
- 9 int fd=open("fifo",O_WRONLY);
- 10 assert(fd!=-1);
- 11 printf("fd=%d\n",fd);
- 12 while(1)
- 13 {
- 14 memset(buff,0,127);
- 15 gets(buff);
- 16 if(strcmp(buff,"end")==0)
- 17 {
- 18 break;
- 19 }
- 20 write(fd,buff,127);
- 21 }
- 22 close(fd);
- 23 return 0;
- 24 }