Linux系统编程--命名管道

上一节我谈到匿名管道,适合在有亲缘的进程上使用,这节我们谈及一下命名管道(FIFO)。

命名管道定义

命名管道是一个设备文件,因此即使两个进程不存在亲缘关系, 可以访问该路径,就能通过FIFO相互通讯。

FIFO先进先出,是半双工通讯。

下面就聊聊命名管道相关函数

函数名作用返回值注意 
mkfifo创建管道

0:成功

-1:失败

  
open打开管道成功返回文件描述符,失败则返回-1  
write写入管道成功返回写入字节数,失败返回0或者-1  
read读管道成功返回读取字节数,失败返回0或者-1  

下面我们直接看demo代码。

首先我们创建一个pipe1.c代码,用来创建管道和写入

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(){
    int ret = mkfifo("./fifo",S_IFIFO|644);//创建管道
    if(ret < 0){
        perror("mkfifo error");
        exit(1);
    }
    int fd = open("./fifo",O_WRONLY);//打开管道
    if(fd <  0){
        perror("open error");
        exit(1);
    }
    char buf[BUFSIZ]="HELLO WORLD";
    while(1){
        ret = write(fd,buf,strlen(buf));//写入管道
        sleep(1);
    }
    
}

然后我们创建一个pipe2.c文件,用来读取管道

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main(){
    int fd = open("./fifo",O_RDONLY);
    if (fd < 0){
        perror("open error");
        exit(1);
    }
    while(1){
        char buf[BUFSIZ]={0};
        int ret = read(fd,buf,sizeof(buf));
        if(ret>0){
            printf("read buffer =%s\r\n",buf);
        }
    }
    
}

执行以上代码,发现执行pipe2.c代码,会收到pipe1.c代码发来的数据。在文件夹下也找到"fifo"文件,说明命名管道其实是文件操作。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值