有名管道FIFO依赖于文件系统,使得不仅仅是亲缘进程,同主机任意进程间也可实现通信。
有名管道和普通文件一样具有磁盘存放路径、文件权限和其他属性。
但是有名管道并没有在磁盘中存放真正的信息,他存储的通信信息在内存中,两个进程通信结束后自动消失。
通信结束后,有名管道的文件路径本身仍然存在。
API:
\*创建一个有名管道*\
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(__const char *__path,__mode_t __mode);
创建成功则返回0,否则返回0
亲缘关系进程间使用有名管道(读写时需要确定对方的存在否则阻塞):
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
int main(){
int pid;
int error;
unlink("FIFO"); //delete FIFO
error=mkfifo("FIFO",0777);
if(error){
printf("can not touch FIFO\n");
return -1;
}
pid=fork();
if(pid==0){ //child
int fd;
char buf[128];
memset(buf,'\0',128);
fd=open("FIFO",O_RDONLY);
close(fd);
//read(fd,buf,10);
}
else{ //father
int fd;
fd=open("FIFO",O_WRONLY);
sleep(1);
printf("to write\n");
write(fd,"helloworld",10);
printf("write done\n");
}
return 0;
}
输出结果:
to write
(子进程阻塞在write函数)