FIFO,也称为命名管道,它是一种文件类型。
特点:
1. FIFO可以在无关的进程之间交换数据,与无名管道不同。
2. FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。
原型:
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
/*
RETURN VALUE
On success mkfifo() and mkfifoat() return 0(成功返回0). In the case of an error,
-1(失败返回-1) is returned (in which case, errno is set appropriately).
*/
其中的 mode 参数与open
函数中的 mode 相同。一旦创建了一个 FIFO,就可以用一般的文件I/O函数操作它。
当 open 一个FIFO时,是否设置非阻塞标志(O_NONBLOCK
)的区别:
若没有指定O_NONBLOCK
(默认),只读 open 要阻塞到某个其他进程为写而打开此 FIFO。类似的,只写 open 要阻塞到某个其他进程为读而打开它。
若指定了O_NONBLOCK
,则只读 open 立即返回。而只写 open 将出错返回 -1 如果没有进程已经为读而打开该 FIFO,其errno置ENXIO。
代码示例:
FIFO的通信方式类似于在进程中使用文件来传输数据,只不过FIFO类型文件同时具有管道的特性。在数据读出时,FIFO管道中同时清除数据,并且“先进先出”。下面的例子演示了使用 FIFO 进行 IPC 的过程:
write.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int fd = 0;
int cnt = 0;
char *str = "hello from write";
if((fd = open("./file1",O_WRONLY)) == -1) //以只写方式打开FIFO文件
{
printf("open file1 failed\n");
}else
{
printf("open file1 success\n");
}
while(1)
{
cnt++;
write(fd,str,strlen(str)); //写到FIFO中
sleep(1); //休眠一秒再写
if(cnt == 5) //写五次
{
break;
}
}
close(fd); //关闭FIFO文件
return 0;
}
read.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int fd = 0;
int nread = 0;
char buf[16];
if((mkfifo("./file1",0600)) == -1 && errno != EEXIST)//创建FIFO管道
{
printf("creat fifo failed\n");
perror("reason");
}
if((fd = open("./file1",O_RDONLY)) == -1) //以只读方式打开FIFO文件
{
printf("open file1 failed\n");
}
while((nread = read(fd,buf,16)) > 0) //读内容
{
printf("read %d byte,context:%s\n",nread,buf);
}
close(fd); //关闭FIFO文件
return 0;
}