有名管道也就命名管道
函数原型
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *filename,mode_t mode);
其中mode参数与open函数中的mode相同,一旦创建了一个FIFO,就可以用一般I/O函数操作它。
mode则指定了文件的读写权限。
有名管道也被称为FIFO文件,是一种特殊的文件。由于linux所有的事物都可以被视为文件,所有对有名管道的使用也就变得与文件操作非常统一。
例子
创建有名管道
#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("file you\n");
}else{
printf("mkfifo success\n");
}
}
return 0;
}
有名管道特点:
有名字,存储于普通文件系统中
任何具有相应权限的进程都可以使用open()来获取FIFO的文件描述符
跟普通文件一样,用read()和write()来读和写
不能用lseek()来定位
具有写入原子性,支持多写者同时进行操作而数据不会互相践踏
创建有名管道还可以省略写成
#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;
}
打开有名管道
当open一个FIFO时,是否设置非阻塞标志(O_NONBLOCK)的区别
若没有指定O_NONBLOCK(默认),只读open要阻塞到某个其它进程为写而打开此FIFO。类似的,只写open要阻塞到某个其它进程为读而打开
现在分两个文件,一个用于写,一个用于读
读:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
//int mkfifo(const char *pathname, mode_t mode);
int main()
{
char buf[30] = {0};
int n_read = 0;
if(mkfifo("./file",0600) == -1 && errno != EEXIST){
printf("mkfifo faill\n");
}
int fd = open("./file",O_RDONLY);
printf("write open success\n");
n_read = read(fd, buf, 30);
printf("read %d byte from fifo, context :%s\n",n_read, buf);
close(fd);
return 0;
}
写:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
//int mkfifo(const char *pathname, mode_t mode);
int main()
{
int cnt = 0;
char *str = "message from fifo";
int fd = open("./file",O_WRONLY);
printf("write open success\n");
while(1){
cnt++;
write(fd, str, strlen(str));
sleep(1);
if(cnt == 5){
break;
}
}
close(fd);
return 0;
}