FIFO,也称为命名管道,它是一种文件类型。
特点:
1、FIFO可以在无关进程之间交换数据,与无名管道不同。
2、FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。
api原型:(man 3 mkfifo查看)
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
mode参数与open函数中mode相同。一旦创建一个FIFO,就可以用一般的文件I/O(open、read、write)函数操作它。
1、代码演示,生成file文件:
#include <sys/types.h>
#include <sys/stat.h>
// int mkfifo(const char *pathname, mode_t mode);
int main()
{
mkfifo("./file",0600);
return 0;
}
编译运行,ls -l 可以看到生成一个file文件
total 20
-rwxr-xr-x 1 CLC book 8379 Apr 10 22:22 a.out
-rw-r--r-- 1 CLC book 573 Apr 10 21:53 demo1.c
-rw-r--r-- 1 CLC book 148 Apr 10 22:22 demo2.c
prw------- 1 CLC book 0 Apr 10 22:22 file
2、添加调试信息:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
// int mkfifo(const char *pathname, mode_t mode);
int main()
{
int ret=mkfifo("./file",0600);
if(ret==0){
printf("mkfifo success\n");
}
if(ret==-1){
printf("mkfifo fail\n");
perror("why");
}
return 0;
}
修改:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
// int mkfifo(const char *pathname, mode_t mode);
int main()
{
if(mkfifo("./file",0600)==-1&&errno==EEXIST){
printf("mkfifo fail\n");
perror("why");
}
else{
if(errno==EEXIST){
printf("have file\n");
}
else
printf("mkfifo success");
}
return 0;
}
当文件夹中没有file文件时,创建file并提示创建成功;否则提示创建失败,并打印原因
3、最终修改为不管文件夹有没有file文件,都不报错,也不报成功
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
// int mkfifo(const char *pathname, mode_t mode);
int main()
{
if((mkfifo("./file",0600)==-1)&&errno!=EEXIST){
printf("mkfifo fail\n");
perror("why");
}
return 0;
}