无名管道类似于无名管道,一般都会和无名管道比较着来说
无名管道的创建
特点
- 用于同一台PC机的两个进程,可以是亲缘进程,也可以是不相关的进程
- 通过文件IO操作管道
- 不支持lseek等跳转光标函数
- 遵循先进先出的原则
- 存在于文件系统中,可以看到。文件类型为p(管道文件)
读写操作
读操作
- 如果之前fifo管道内没有数据,读进程就会一直阻塞,一直阻塞到有数据写入或FIFO管道写端关闭
写操作
- 只要FIFO中有空间,数据就可以写入,若空间不足,写进程就会阻塞,直到数据全部写入
读端代码
/*************************************************************************
> File Name: fifo_one.c
> 功能:创建一个管道,此程序用来读出管道中的数据
> Mail:
> Created Time: Thu 15 Aug 2019 12:45:50 AM PDT
************************************************************************/
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{
int fifo=0;
int fd=0;
int ret=0;
char buf[1024]={0};
//创建一个管道
fifo= mkfifo("/home/linux/Desktop/myfifo",0666);
if(fifo<0)
{
perror("mkfifo error");
exit(-1);
}
//以只读模式,打开一个管道
fd=open("/home/linux/Desktop/myfifo",O_RDONLY);
if(fd<0)
{
perror("open error");
exit(-2);
}
while(1)
{
ret=read(fd,buf,sizeof(buf));
if(ret<0)
{
perror("read error");
exit(-3);
}
if(ret==0)
{
printf("这次什么也没有读到\n");
exit(66);
}
printf("这次读到的东西是%s\n",buf);
memset(buf,0,sizeof(buf));
}
close(fd);
remove("/home/linux/Desktop/myfifo");
return 0;
}
写端代码
/*************************************************************************
> File Name: fifo_two.c
> Author:
> Mail:
> Created Time: Thu 15 Aug 2019 01:34:46 AM PDT
************************************************************************/
#include<stdio.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{
int fd=0;
int ret=0;
char buf[1024]={0};
//以只写模式打开一个管道文件
fd=open("/home/linux/Desktop/myfifo",O_WRONLY);
if(fd<0)
{
perror("open error");
exit(-1);
}
while(1)
{
gets(buf);
write(fd,buf,sizeof(buf));
memset(buf,0,sizeof(buf));
}
return 0;
}