在前面的博客中,提过进程的一种通信方式,匿名管道,匿名管道有个缺点,就是只适合有亲缘关系的进程之间通信。那么为了提供给两个任意进程之间进行通信,又提出了一种方式叫命名管道。
下边我们来实现一下。首先编写两个.c文件,client.c(用来写),server.c(用来读)。
client.c(写端):
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
int main(){
int fd=open("mypipe",O_WRONLY);
if(fd<0){
printf("open error\n");
return 0;
}
char buf[1024]={0};
while(1){
scanf("%s",buf);
int ret=write(fd,buf,sizeof(buf));
if(ret<0)
{
printf("write error");
break;
}
}
close(fd);
}
"client.c" 24L, 379C
server.c(读端):
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include <fcntl.h>
#include<string.h>
#include<unistd.h>
int main()
{
umask(0);
if(mkfifo("./mypipe",0666|S_IFIFO<0))
{
perror("mkfifo");
return 1;
}
int fd=open("mypipe",O_RDONLY);
if(fd<0){
printf("open error\n");
return 0;
}
char buf[1024]={0};
while(1){
int ret=read(fd,buf,sizeof(buf));
if(ret<=0){
printf("read end or error\n");
break;
}
printf("%s\n",buf);
}
close(fd);
}
~
~
我们再来编写个makefile用来同时编译两个文件:
![](https://i-blog.csdnimg.cn/blog_migrate/eb9c79ff64bc82d189e321eeaedb358c.png)
然后开启两个终端运行程序,就会出现以下情况:
![](https://i-blog.csdnimg.cn/blog_migrate/78902790d192687d2a792ee061f130d4.png)
我们看到,client.c写到命名管道中的文件,server.c读了出来并且打印到屏幕上,成功地达到了通信的目的。