有名字的文件,所以每个进程都能打开,针对所有没有亲缘关系的进程
- 检查文件是否存在access()
- 创建有名管道mkfifo()
- 共享文件夹里面不能创建,windows不支持管道文件
- 只需要在不同的进程里面执行open()打开管道,就可以用write()、read()操作
- 有名管道具有写入原子性
- 经典的管道模型,多个进程同时负责写,一个进程负责读。
以下代码是通过有名管道写和读一段数据:
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
//access()检查文件是否存在
if(access("myfifo",F_OK)!=0){
//不存在就创建
int mk=mkfifo("./myfifo",0777);
if(mk==-1){ //创建失败 打印错误 并退出
perror("create mk failed");
return -1;
}
}
//创建无名管道并打开
int fifo=open("./myfifo",O_RDWR);
if(fifo==-1){//打开失败,退出
perror("create fifo failed");
return -1;
}
//写数据
char buf[128];
while(1){
memset(buf,0,128);
//bzero(buf,128);
fgets(buf,sizeof(buf),stdin);
write(fifo,buf,strlen(buf));
}
//如果要读数据将写数据的代码换为:
/*
//读数据
char buf[128];
while(1){
memset(buf,0,sizeof(buf));//可以为:bzero(buf,128)
read(fifo,buf,sizeof(buf));
printf("from write: %s\n",buf);
}
*/
close(fifo);
return 0;
}