进程通信之命名管道

  在前面的博客中,提过进程的一种通信方式,匿名管道,匿名管道有个缺点,就是只适合有亲缘关系的进程之间通信。那么为了提供给两个任意进程之间进行通信,又提出了一种方式叫命名管道。
   下边我们来实现一下。首先编写两个.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用来同时编译两个文件:
然后开启两个终端运行程序,就会出现以下情况:

我们看到,client.c写到命名管道中的文件,server.c读了出来并且打印到屏幕上,成功地达到了通信的目的。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值