命名管道:
可以用于同一主机上任意进程间通信—管道缓冲区具有标识符
命名管道:mkfifo filename 创建一个管道文件
命名管道本质上依然是内核中的一块缓存区,但是命名管道有名字具有标识符,而这个标识符就是一个可见于文件系统的管道类型文件,多个进程可以通过打开同一个管道文件访问同一块内核中的缓冲区实现通信
代码操作:int mkfifo(char *path,int mode);
对管道的读写操作,仍然是IO操作
打开特性:
若以只读方式打开命名管道文件,则会阻塞,直到这个管道文件被以写的方式打开(即读写打开)
若以只写方式打开命名管道文件,则会阻塞,直到这个管道文件被以读的方式打开(即读写打开)
//读文件.c
#include<stdio.h> //printf
#include<unistd.h> //fork
#include <sys/stat.h> //mkfifo open
#include <unistd.h> //read
#include <sys/types.h> //open
#include <fcntl.h> //open
#include <errno.h> //errno
int main(int argc,char *argv[]) //运行参数个数 运行参数首地址
{
//设置权限
umask(0);
//1.创建管道文件
char *fifo_name="./test.fifo"; //定义管道路径
//int mkfifo(char *path,int mode);
int ret=mkfifo(fifo_name,0664);
if(ret<0 && errno!=EEXIST){
perror("mkfifo error");
return -1;
}
//2.打开管道文件
//open(文件名,打开方式,权限)
int fd=open(fifo_name,O_RDONLY);
if(fd<0){
perror("open error"); //打开失败
return -1;
}
printf("打开成功\n");
//3.读取文件数据
while(1){
char buf[1024]={0};
int ret=read(fd,buf,1023);
if(ret<0){
perror("read error");
return -1;
}else if(ret==0){
printf("all write closed\n");
return -1;
}
printf("buf:%s\n");
}
close(fd);
return 0;
}
//写文件
#include<stdio.h> //printf
#include <errno.h> //errno
#include<string.h> //strlen
#include<fcntl.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<unistd.h>
int main(int argc,char* argv[])
{
umask(0); //权限掩码为0
//1.创建一个管道文件
char* fifo_name="./test.fifo"; //文件路径
//int mafifo(char *path,int mode);
int ret=mkfifo(fifo_name,0664);
if(ret<0 && errno!=EEXIST){ //文件创建失败
perror("mkfifo error");
return -1;
}
//2.打开文件
int fd=open(fifo_name,O_WRONLY);
if(fd<0){
perror("open error");
return -1;
}
//3.写入数据
while(1){
char buf[1024]={0}; //定义存储数据大小
scanf("%s",buf); //写入数据
int res=write(fd,buf,strlen(buf)); //写入数据到文件
if(res<0){
perror("write error"); //写入数据失败
return -1;
}
}
//4.关闭文件
close(fd);
return 0;
}