管道是进程间通信的手段之一,在这之前,普通文件是最基本的通信方式,而普通文件通信的问题在于,A进程对文件写进了内容,B进程无法感知这种变化,而管道正好解决了这种问题。
管道的使用方法
创建管道的进程fifoA:- 创建管道
- 打开管道
- 写数据
- 关闭管道
- 删除管道
接收数据的进程fifoB
- 打开管道
- 读取数据
- 关闭管道
管道文件只能由其创建者删除,而接受者在关闭后重新打开,可以继续接收管道的数据。,举个栗子。。
fifoA.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
int fd;
int i;
void handle(int s){
if(s==SIGINT){
close(fd);
unlink("main.pipo");
exit(-1);
}
//close fifo
//delete fifo
}
int main(){
//craete a fifo file
mkfifo("main.fifo",0666);
//open the fifo
fd=open("main.fifo",O_RDWR);
//write data
while(1){
write(fd,&i,4);
sleep(1);
++i;
}
return 0;
}
fifoB.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
int fd;
int i;
void handle(int s){
if(s==SIGINT){
close(fd);
exit(-1);
}
}
int main(){
signal(SIGINT,handle);
//open fifo file
fd=open("main.fifo",O_RDONLY);
i=0;
while(1){
read(fd,&i,4);
printf("%d\n",i);
}
return 0;
}
其中关闭管道由一个信号处理事件完成。先打开A,然后打开B,中间可以保持A开启,而B多次关闭打开,查看运行结果,这里就不再截图了。
- 没有数据时,read阻塞,而且read后数据被删除
- 数据有序
- 打开的描述符号可以读写
- 管道文件关闭后,数据不持久
- 管道的数据存储在内核缓冲区中