命名管道FIFO
FIFO (First in, First out)不同于匿名管道pipe之处在于它提供一个路径名与之关联,以FIFO的文件形式存储于文件系统中,因此,即使进程与创建FIFO的进程不存在亲缘关系,只要可以访问该路径,就能够通过FIFO相互通信。当一个进程以读(r)的方式打开该文件,而另一个进程以写(w)的方式打开该文件,那么内核就会在这两个进程之间建立管道,所以FIFO实际上也由内核管理,不与硬盘打交道。之所以叫FIFO,是因为管道本质上是一个先进先出的队列数据结构,最早放入的数据被最先读出来,从而保证信息交流的顺序。FIFO只是借用了文件系统来为管道命名。写模式的进程向FIFO文件中写入,而读模式的进程从FIFO文件中读出。当删除FIFO文件时,管道连接也随之消失。
函数头文件、相关参数和返回值
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *filename, mode_t mode);
filename参数是创建管道所在的地址,mode参数是设置创建的管道权限,常用的有:
O_RDWR(读写方式):不会导致阻塞
O_RDONLY(只读方式):调用open()函数的进程将会被阻塞,直到有写方打开管道
O_WRONLY(写方式):也会阻塞,直到有读方打开管道
返回值:若成功,返回0;若出错,返回-1
代码示例
read.c
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include<errno.h>
#include <fcntl.h>
int main()
{
char buf[30] = {0};
int nread = 0;
if( (mkfifo("./file",0600) == -1) && errno!=EEXIST)//如果错误的原因是已存在
{
printf("mkfifo failuer\n");
perror("why");
}
int fd = open("./file",O_RDONLY);
printf("open success\n");
while(1){
nread = read(fd,buf,30);
printf("read %d byte from fifo,context:%s\n",nread,buf);
}
close(fd);
return 0;
}
write.c
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include<errno.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int cnt = 0;
char *str = "message from fifo";
int fd = open("./file",O_WRONLY);
printf("write open success\n");
while(1){
write(fd, str, strlen(str));
sleep(1);
}
close(fd);
return 0;
}
编译运行