一、有名管道
对应管道文件,可用于任意进程之间进行通信,打开管道时可指定读写方式,通过文件IO操作,内容存放在内存中。
1.1 API
#include <unistd.h>
#include <fcntl.h>
int mkfifo(const char *path, mode_t mode);
成功时返回0,失败时返回EOF
path 创建的管道文件路径
mode 管道文件的权限,如0666
1.2写操作demo
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
int main(){
int re;
int fd;
char buf[32];
unlink("/myfifo"); //删除myfifo
re = mkfifo("/myfifo",0666);
if(re==-1){
perror(“mkfifo”);
return -1;
}
fd = open("/myfifo",O_WRONLY);
if(fd<0){
perror(“open”);
return -1;
}
strcpy(buf,“fifo write test”);
while(1){
write(fd,buf,strlen(buf));
sleep(1);
}
}
1.3 读操作
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
int main(){
int re;
int fd;
char buf[32];
fd = open("/myfifo",O_RDONLY);
if(fd<0){
perror(“open”);
return -1;
}
while(1){
memset(buf,0,32);
read(fd,buf,32);
printf("%s\n",buf);
sleep(1);
}
}
注释 :
1、管道面试:
(1)、有名管道和无名管道的区别?
有名管道可以在任意两个进程间通信,无名管道只能在父子进程间通信;
(2)、写入管道文件的数据在内存上还是磁盘上?
无论是有名管道还是无名管道,管道文件的数据在内存存放;
p 管道文件 存放在内存中 不可能在磁盘中存储数据 ;临时存放;断电重启关闭程序会丢失数据;
衍生的一个问题:为什么不能通过普通文件实现进程间的通信?
普通文件存放在磁盘上,读写速度慢;磁盘(永久存储)<<内存(临时存储)<<寄存器(速度);磁盘>>内存>>寄存器(容量);
(3)、管道通信方式是单工、半双工还是全双工?
管道通信方式是半双工;
单工:数据传输只支持数据在一个方向上传输;在同一时间只有一方能接受或发送信息