Linux进程间通信之命名管道篇

创建命名管道

  • 命名管道可以从命令行上创建
    mkfifo filename

  • 命名管道也可以从程序里创建

int mkfifo(const char *filename, mode_t mode);

//创建命名管道
int main(){
    mkfifo("fifo", 0644);
    return 0;
}

匿名管道与命名管道的区别

  1. 匿名管道由pipe函数创建并打开
  2. 命名管道由mkfifo函数创建,用open打开
  3. FIFO(命名管道)与pipe(匿名管道)之间唯一的区别在他们创建与打开的方式不同,一旦这些工作完成后,它们具有相同的意义。

命名管道的打开规则

1)如果当前打开操作是为读而打开FIFO时

  • O_NONBLOCK disable:阻塞直到有相应进程为写而打开该FIFO
  • O_NONBLOCK enable:立即返回成功

2)如果当前打开操作是为写而打开FIFO时

  • O_NONBLOCK disable:阻塞直到有相应进程为读而打开该FIFO
  • O_NONBLOCK enable:立即返回失败,错误码为ENXIO

命名管道实现进程间通信

writer.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main(){
    int fd = open("./myfifo", O_WRONLY);
    if(fd < 0){
        perror("open error");
        return 1;
    }
    while(1){
        char buf[1024] = {0};
        printf("Please Enter:");
        fflush(stdout);
        ssize_t read_size = read(0, buf, sizeof(buf) - 1);
        if(read_size < 0){
            perror("read error");
            return 1;
        } 
        if(read_size == 0){
            printf("read done!\n");
            return 0;
        }
        buf[read_size] = '\0';
        write(fd, buf, strlen(buf));
    }
    close(fd);
    return 0;
}

reader.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main(){
    int fd = open("./myfifo", O_RDONLY);
    if(fd < 0){
        perror("open error");
        return 1;
    }
    while(1){
        char buf[1024] = {0};
        printf("Please wait ...\n");
        ssize_t read_size = read(fd, buf, sizeof(buf) - 1);
        if(read_size < 0){
            perror("read error");
            return 1;
        }
        if(read_size == 0){
            printf("read done!\n");
            return 0;
        }
        buf[read_size] = '\0';
        printf("client say# %s", buf);
    }
    close(fd);
    return 0;
}

效果如下:
描述

详细代码请参考Git(点击Git即可)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值