二十一、Linux系统编程-管道(二)命名管道(FIFO)、匿名管道与命名管道区别、命名管道的打开规则
来源:互联网 发布:大学生就业数据统计 编辑:程序博客网 时间:2024/05/20 07:33
一、命名管道(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时
- O_NONBLOCKdisable:阻塞直到有相应进程为写而打开该FIFO
- O_NONBLOCKenable:立刻返回成功
- 如果当前打开操作是为写而打开FIFO时
- O_NONBLOCKdisable:阻塞直到有相应进程为读而打开该FIFO
- 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 0
- 二十一、Linux系统编程-管道(二)命名管道(FIFO)、匿名管道与命名管道区别、命名管道的打开规则
- 匿名管道 与 命名管道/FIFO管道 的特点
- Linux系统编程之管道:匿名管道pipe与命名管道fifo
- 匿名管道、命名管道
- 匿名管道 与 命名管道
- 匿名管道与命名管道
- Linux命名管道FIFO
- 【Linux】命名管道FIFO
- Linux 命名管道FIFO
- Linux命名管道FIFO的读写规则
- Linux命名管道FIFO的读写规则
- Linux命名管道FIFO的读写规则
- Linux命名管道FIFO的读写规则
- 命名管道(FIFO)
- 命名管道(FIFO)
- 命名管道(FIFO)
- c# 管道通信-命名管道(二)
- 匿名管道和命名管道
- 数据对齐
- C++中的引用问题
- Android Fragment 真正的完全解析(上)
- 30天自制操作系统day5
- 9.cpp
- 二十一、Linux系统编程-管道(二)命名管道(FIFO)、匿名管道与命名管道区别、命名管道的打开规则
- ClearspaceMUCTranscriptManager的roomEvents是否存在并发问题
- PE文件结构(一)
- 第六周项目1——图形用户界面应用程序开发初体验
- 编程之美2015资格赛#3
- Ubuntu的配置设置
- org.json typedismatch
- C++用位运算实现循环移位
- C++Primer学习笔记(12)类