一、fifo 的基本概念和创建
1、特点:
(1)有名管道;
(2)伪文件:在磁盘上是一个管道文件,但对其读写操作,该文件大小都为 0。
注意:pipe 文件在磁盘上,ls -l 能查看到,但文件内数据不在磁盘上,是在内存上
(3)数据通过伪文件存放在内核区,本质仍然是内核中的缓冲区。
(4) 半双工的通信方式。
2、使用场景
没有血缘关系的进程间通信
3、创建方式
(1)命令:mkfifo 管道名
(2)函数:
int mkfifo(const char *pathname, mode_t mode); // 使用 跟 mkdir 差不多
二、fifo 实现进程间通信
1、fifo_r.c 读进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[])
{
if(argc != 2){
printf("./a.out fifoname\n");
return -1;
}
//1. 打开文件
int fd = open(argv[1], O_RDONLY);
if(fd < 0){
perror("open err");
return -1;
}
//2. 循环读取数据 -- 显示到屏幕
char buf[256] = {0};
while(1){
int ret = read(fd, buf, sizeof(buf));
if(ret > 0){
// 读到数据
printf("%s\n", buf);
}
else if(ret == 0){
// 读到末尾 -- 写端全部关闭
printf("write closed\n");
break;
}
else {
perror("read err");
break;
}
}
//3. 关闭
close(fd);
return 0;
}
2、fifo_w.c 写进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[])
{
if(argc != 2){
printf("./a.out fifoname\n");
return -1;
}
//1. 打开fifo文件
printf("begin open....\n");
int fd = open(argv[1], O_WRONLY); // open 函数会等待另外一段的读打开,否则阻塞
if(fd < 0){
perror("open err");
exit(1);
}
printf("end open....\n");
//2. 循环写入数据
char buf[256] = {0};
int i = 0;
while(1){
memset(buf, 0x00, sizeof(buf));
sprintf(buf, "xiaoming-%04d", i++);
write(fd, buf, strlen(buf));
sleep(1); //防止写的太快了
}
//3. 关闭
close(fd);
return 0;
}