简介
有名管道可以在任意两个进程之间通信,命名管道通常被称为FIFO,创建有名 管道的进程可以给管道取名字以及路径,该路径名是以特殊的⽂件存在放在⽂ 件系统中,因此两个进程可以通过访问该路径来建⽴联系,进⾏进程间的数据 交换,有名管道和⽆名管道都遵循先进先出的原则。 访问命名管道⽂件与访问⽂件系统中的其他⽂件相似,都是需要先打开⽂件, 然后对⽂件进⾏读写数据。
有名管道是⼀个特殊的⽂件,它和普通的⽂件⼀样具有磁盘存放路径,⽂件权 限和其他属性,但是两者⼜有区别,有名管道并不会在磁盘中存放真正的信 息,信息存放在内存中。通讯的两个进程结束后,信息会⾃动消失,但管道⽂件路径依然存在。
有名管道的创建:
1、可以通过命令⾏创建: mkfifo filename
2、通过系统函数调⽤创建:
例子
例:mkfifo的使用
#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int main(){char buff[100]={0};if(access("hello",F_OK)!=0){int pipe_fd=mkfifo("hello",0777);if(pipe_fd==-1){printf("create faild");return -1;}}int fd=open("hello",O_RDWR);write(fd,"hello word!",20);if(read(fd,buff,20)!=-1)printf("receive data=%s\n",buff);close(fd);return 0;}
fork()什么时候创建失败
1.内存满的时候
2.内存不够用
例:父子进程之间用有名管道进行通讯
#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <sys/wait.h>#include <stdlib.h>#include <fcntl.h>int main(){char buff[100]={0};if(access("hello1",F_OK)!=0){int pipe_fd=mkfifo("hello1",0777);if(pipe_fd==-1){printf("create faild");return -1;}}pid_t pid=fork();if(pid==-1){return -1;}if(pid>0){int fd=open("hello1",O_WRONLY);write(fd,"hello",20);close(fd);wait(NULL);}else{int fd=open("hello1",O_RDONLY);read(fd,buff,20);close(fd);printf("subprocess data:%s\n",buff);exit(0);}printf("end\n");return 0;}
