二十一、Linux系统编程-管道(二)命名管道(FIFO)、匿名管道与命名管道区别、命名管道的打开规则

一、命名管道(FIFO)
        创建匿名管道实际上是创建一个64K大小的内存缓冲区,匿名管道的一个限制就是只能在具有共同祖先(具有亲缘关系)的进程间通信。如果我们想在不相关的进程之间交换数据,可以使用FIFO文件来做这项工作,它经常被称为命名管道。命名管道是一种特殊类型的文件。
函数声明:
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
函数参数:打开路径,模式
返回值:成功返回0,失败返回-1
二、匿名管道与命名管道区别
  • 匿名管道由pipe函数创建并打开。
  • 命名管道由mkfifo函数创建,打开用open
  • FIFO(命名管道)与pipe(匿名管道)之间唯一的区别在它们创建与打开的方式不同,一量这些工作完成之后,它们具有相同的语义。
三、命名管道的打开规则

  • 如果当前打开操作是为读而打开FIFO时
  1. O_NONBLOCKdisable:阻塞直到有相应进程为写而打开该FIFO
  2. O_NONBLOCKenable:立刻返回成功
  • 如果当前打开操作是为写而打开FIFO时
  1. O_NONBLOCKdisable:阻塞直到有相应进程为读而打开该FIFO
  2. O_NONBLOCKenable:立刻返回失败,错误码为ENXIO
示例:进程之间用管道传递数据:
写端程序:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

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

#define ERR_EXIT(m) \
        do \
        { \
                perror(m); \
                exit(EXIT_FAILURE); \
        }while(0)

int main()
{
        char buf[1024];
        mkfifo("tp",0644);
        int infd;
        infd = open("aa.txt",O_RDONLY);
        if (infd == -1)
                ERR_EXIT("open error");
        int outfd;
        outfd = open("tp",O_WRONLY);
        if (outfd == -1)
                ERR_EXIT("open error");
        int n;
        while((n = read(infd,buf,1024)) > 0)
        {
                write(outfd,buf,n);
        }
        printf("write succ\n");
        return 0;
}

读端程序:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

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

#define ERR_EXIT(m) \
        do \
        { \
                perror(m); \
                exit(EXIT_FAILURE); \
        }while(0)

int main()
{
        char buf[1024];
        int infd;
        infd = open("tp",O_RDONLY);
        if (infd == -1)
                ERR_EXIT("open error");
        int n;
        while((n = read(infd,buf,1024)) > 0)
                printf("%s\n",buf);
        printf("write succ\n");
        return 0;
}
程序运行结果:读端程序把写端程序传递过来的数据打印出来


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值