目录
可以使用于无血缘关系的管道之间的通信,使不相关的进程也能交换数据。其本质是通过一种队列的方式来进行的。类似于pipe,也是创建了一个管道的伪文件,
两种创建fofo管道的伪文件的方法
- mkfifo myfifo 命令创建
- 也可以用函数 int mkfifo(const char *pathname, mode_t mode)
内核会针对fifo文件开辟一个缓冲区,操作fifo文件,可以操作缓冲区,实现进程间通信--实际上就是文件读写
实现通信写端
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char * argv[])
{
if(argc != 2){
printf("./a.out fifoname\n");
return -1;
}
// 当前目录有一个 myfifo 文件
//打开fifo文件
printf("begin open ....\n");
int fd = open(argv[1],O_WRONLY);
printf("end open ....\n");
//写
char buf[256];
int num = 1;
while(1){
memset(buf,0x00,sizeof(buf)); //清理缓冲区
sprintf(buf,"xiaoming%04d",num++);
write(fd,buf,strlen(buf));
sleep(1);
//循环写
}
//关闭描述符
close(fd);
return 0;
}
借助buf将进程中的内容写入伪文件fd中。
实现通信读端
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char *argv[])
{
if(argc != 2){
printf("./a.out fifoname\n");
return -1;
}
printf("begin oepn read...\n");
int fd = open(argv[1],O_RDONLY);
printf("end oepn read...\n");
char buf[256];
int ret;
while(1){
//循环读
memset(buf,0x00,sizeof(buf));
ret = read(fd,buf,sizeof(buf));
if(ret > 0){
printf("read:%s\n",buf);
}
}
close(fd);
return 0;
}
在fd伪文件中的数据读出来到buf中,那原来位于fd中的数据就没有了。
open注意事项(使用fifo时)
打开fifo文件的时候,read端会阻塞等待write端open,write端同理,也会阻塞等待另外一端打开