-
什么是命名管道
匿名管道应用的一个限制就是只能在具有亲缘关系的进程之间进行通信,如果我们想在没有关系的两个进程之间进行通信,可以使用fifo来实现,这种实现方式被称为命名管道。命名管道是一种特殊类型的文件。
-
创建一个命名管道
1.命名管道可以从命令行上创建:
$ mkfifo filename
2.命名管道也可以使用代码创建,相关函数有:
int mkfifo(const char* filename,mode_t mode);
创建命名管道:
int main(int argc,char* argv[])
{
mkfifo("fifo",0644);
return 0;
}
-
匿名管道与命名管道的区别
- 匿名管道由pipe函数创建并打开
- 命名管道由mkfifo函数创建,打开用open
- 匿名管道只能用于有亲缘关系的进程间通信,而命名管道是任何关系的进程都能进行通信
- fifo(命名管道)与pipe(匿名管道)之间的区别在于它们的创建与打开方式不同,一旦这些工作完成后,它们的共同作用仍旧是进行进程间通信。
-
实例:
使用命名管道实现server&client通信
具体实现代码如下:
makefile:
.PHONY:all
all : server client
server : server.c
gcc - o $@ $ ^
client:client.c
gcc - o $@ $ ^
.PHONY:clean
clean :
rm - f server client
server.c:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define MAX 1024
int main()
{
if(mkfifo("./fifo",0644)<0)//创建命名管道,并判断是否创建成功
{
perror("mkfifo error!\n");
return 1;
}
int fd=open("./fifo",O_RDONLY);//让./fifo以只读方式打开
if(fd<0)
{
perror("read error!\n");
return 2;
}
char buf[MAX];
while(1)
{
ssize_t s=read(fd,buf,sizeof(buf)-1);//从管道中读取数据
if(s>0)//读取成功
{
buf[s]=0;
printf("client# %s\n",buf);
}
else if(s==0)
{
printf("client quit,server quit too!\n");
break;
}
else
{
perror("read");
}
}
close(fd);//关闭读端
return 0;
}
client.c:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX 1024
int main()
{
int fd=open("./fifo",O_WRONLY);//把./fifo文件以只写方式打开
if(fd<0)
{
perror("read");
return 1;
}
char buf[MAX];
while(1)
{
printf("Please Enter:> ");
scanf("%s",buf);
write(fd,buf,strlen(buf));//往管道里面写入数据
}
close(fd);//关闭写端
return 0;
}
程序运行结果:
整体效果:
./client运行结果:
./server运行结果: