原型
#include <sys/stat.h>
int mknod(const char* path, mode_t mod, dev_t dev);
int mkfifo(const char* path, mode_t mod);
特点
为了使任意两个进程之间能够通信,就提出了命名管道(named pipe 或 FIFO)。
1、与管道的区别:提供了一个路径名与之关联,以FIFO文件的形式存储于文件系统中,能够实现任何两个进程之间通信。而匿名管道对于文件系统是不可见的,它仅限于在父子进程之间的通信。
2、FIFO是一个设备文件,在文件系统中以文件名的形式存在,因此即使进程与创建FIFO的进程不存在血缘关系也依然可以通信,前提是可以访问该路径。
3、FIFO(first input first output)总是遵循先进先出的原则,即第一个进来的数据会第一个被读走。
注意
函数 mknod 中参数 path 为创建命名管道的全路径; mod 为创建命名管道的模式,指的是其存取权限; dev为设备值,改值取决于文件创建的种类,它只在创建设备文件是才会用到。
返回值:这两个函数都是成功返回 0 ,失败返回 -1
命名管道调用open()打开有可能会阻塞,但是如果以读写方式(O_RDWR)打开则一定不会阻塞;以只读(O_RDONLY)方式打开时,调用open()的函数会被阻塞直到有数据可读;如果以只写方式(O_WRONLY)打开时同样也会被阻塞,知道有以读方式打开该管道
下面利用命名管道,进行简单数据通信
例子
**read:**
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int nread;
char readBuf[30]={0};
if((mkfifo("./file",0600) == -1) && errno != EEXIST){
printf("mkfifo failure\n");
perror("why");
}else{
printf("mkfifo succeed\n");
}
int fd = open("./file",O_RDONLY);
printf("open succeed\n");
while(1){
nread = read(fd,readBuf,30);
if(nread == 0|| readBuf == NULL){
exit(0);
}
printf("read %d bytes from fifo,context:%s",nread,readBuf);
}
close(fd);
return 0;
}
结果:
mkfifo succeed
open succeed
read 12 bytes from fifo,context:hello world
read 12 bytes from fifo,context:hello world
read 12 bytes from fifo,context:hello world
read 12 bytes from fifo,context:hello world
read 12 bytes from fifo,context:hello world
write:
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int cnt = 0;
char *str = "hello world\n";
int fd = open("./file",O_WRONLY);
printf("write open succeed\n");
while(1){
write(fd,str,strlen(str));
sleep(2);
cnt++;
if(cnt == 5){
break;
}
}
printf("write over!\n");
close(fd);
return 0;
}
结果:
write open succeed
write over!
学识浅薄,希望可以帮到您