管道的一个不足之处是没有名字,因此,只能用于具有亲缘关系的进程间通信,在命名管
道(named pipe或FIFO)提出后,该限制得到了克服。FIFO不同于管道之处在于它提供一
个路径名与之关联,以FIFO的文件形式存储于文件系统中。命名管道是一个设备文件,因
此,即使进程与创建FIFO的进程不存在亲缘关系,只要可以访问该路径,就能够通过FIFO
相互通信。值得注意的是,FIFO(first input first output)总是按照先进先出的原则工作,第一
道(named pipe或FIFO)提出后,该限制得到了克服。FIFO不同于管道之处在于它提供一
个路径名与之关联,以FIFO的文件形式存储于文件系统中。命名管道是一个设备文件,因
此,即使进程与创建FIFO的进程不存在亲缘关系,只要可以访问该路径,就能够通过FIFO
相互通信。值得注意的是,FIFO(first input first output)总是按照先进先出的原则工作,第一
个被写入的数据将首先从管道中读出。
管道read端
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#define _PATH_ ". "
#define _SIZE_ 100
int main()
{
int fd=open(_PATH_,O_RDONLY);
if(fd<0)
{
printf("openfile error\n");
return 1;
}
char buf[_SIZE_];
memset(buf,'\0',sizeof(buf));
while(1){
int ret=read(fd,buf,sizeof(buf));
if(ret<=0)
{
printf("read end\n");
break;
}
printf("%s\n",buf);
if(strncmp(buf,"quit",4)==0)
break;
}
close(fd);
return 0;
}
管道write端
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#define _PATH_ ". "
#define _SIZE_ 100
int main()
{
// int ret=mkfifo(_PATH_,0666|S_IFIFO);
int ret=mkfifo(_PATH_,0666);
if(ret==-1)
{
printf("mkfifo is error\n");
return 1;
}
int fd=open(_PATH_,O_WRONLY);
if(fd<0)
{
printf("openfile error\n");
}
char buf[_SIZE_];
memset(buf,'\0',sizeof(buf));
while(1){
scanf("%s",buf);
int ret=write(fd,buf,strlen(buf)+1);
if(ret<0)
{
printf("write error\n");
break;
}
if(strncmp(buf,"quit",4)==0)
break;
}
close(fd);
return 0;
}
测试结果
进入
输入内容
由于Linux中所有的事物都可被视为文件,所以对命名管道的使用也就变得与文件操作非常
的统一,也使它的使用非常方便,同时我们也可以像平常的文件名一样在命令中使使。