FIFO
FIFO,也称为命名管道,它是一种文件类型。
1、特点
FIFO可以在无关的进程之间交换数据,与无名管道不同。
FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。
2、原型
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
// 返回值:成功返回0,出错返回-1
const char *pathname :文件保存地址
mode_t mode:给文件的权限
当 open 一个FIFO时,是否设置非阻塞标志(O_NONBLOCK)的区别:
- 若没有指定O_NONBLOCK(默认),只读 open 要阻塞到某个其他进程为写而打开此 FIFO。类似的,只写 open 要阻塞到某个其他进程为读而打开它。
- 若指定了O_NONBLOCK,则只读 open 立即返回。而只写 open 将出错返回 -1 如果没有进程已经为读而打开该 FIFO,其errno置ENXIO。
3、例子
FIFO的通信方式类似于在进程中使用文件来传输数据,只不过FIFO类型文件同时具有管道的特性。在数据读出时,FIFO管道中同时清除数据,并且“先进先出”。下面的例子演示了使用 FIFO 进行 IPC 的过程:
3.1 read_fifo.c
#include<stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
char buf[128] = {0};
int n_read;
if((mkfifo("./file",0600) == -1) && errno != EEXIST){
printf("Mlfifo Failed!\n");
perror("why");
}
int fd = open("./file",O_RDONLY);
printf("Open Success\n");
while(1){
memset(buf,0,sizeof(buf));
n_read = read(fd,buf,sizeof(buf));
printf("Buf:%s\n",buf );
if(n_read == 0){
printf("Quite\n");
exit(-1);
}
}
close(fd);
return 0;
}
3.2 write_fifo.c
#include<stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
char *buf = "Msg Form Fifo";
int fd = open("./file",O_WRONLY);
printf("Open Scussess\n");
while(1){
write(fd,buf,strlen(buf));
printf("buf:%s\n",buf);
sleep(1);
}
close(fd);
return 0;
}
在两个终端里用 gcc 分别编译和运行上面两个文件,可以看到输出结果如下:
上述例子可以扩展成 客户进程—服务器进程 通信的实例,write_fifo的作用类似于客户端,可以打开多个客户端向一个服务器发送请求信息,read_fifo类似于服务器,它适时监控着FIFO的读端,当有数据时,读出并进行处理,但是有一个关键的问题是,每一个客户端必须预先知道服务器提供的FIFO接口。
4.遇到的问题
起初在共享文件夹(/mnt/hgfs/Share)对read_fifo.c和writr_fifo.c进行编译和执行,提示创建管道失败,报错“open: No such file or directory”。是目录权限的问题。
分析:
1)gdb发现errno=1,即EPERM,操作不被允许。
2)因为,“/mnt/”目录权限为“rwxr-xr-x”,root可写;而其下的“hgfs/”是与Windows主机的共享目录,其权限为“r-xr-xr-x”,虽然此目录下的所有文件及目录均有“rwxrwxrwx”权限,管道也不能创建成功。
3)解决办法:更改管道路径为其他可写路径,如根目录。
疑问:为什么在当前目录可以进行文件读写操作,却不能用于管道通信。