操作系统第3次实验报告:管道
- 姓名:程开
- 学号:201821121060
- 班级:计算1812
1. 编写程序
在服务器上用Vim编写程序:创建一个命名管道,创建两个进程分别对管道进行读fifo_read.c
和写fifo_write.c
fifo_read.c:
#include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/wait.h> #include <fcntl.h> int main(){ int fd=open("myfifo",O_RDONLY); if(fd<0){ printf("管道创建失败"); return -1; }else{ printf("管道两端建立连接\n"); while(1){ char fdread[100]={0}; int n=read(fd,fdread,100); if(n==0){ printf("对方关闭读\n"); break; } printf("读取的信息是:%s\n",fd); } close(fd); return 0; } }
fifo_write.c:
#include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/wait.h> #include <fcntl.h> int main(){ int wd=open("myfifo",O_WRONLY); if(wd<0){ printf("管道创建失败"); return -1; }else{ printf("管道两端建立连接\n"); while(1){ char wdwrite[100]={0}; fgets(wdwrite,100,stdin); if(strncmp(wdwrite,"shut down",8)==0) break; write(wd,wdwrite,strlen(wdwrite)); } close(wd); } return 0; }
以及一份创建管道的c程序:
int pipe = mkfifo("myfifo",0777);
2. 分析运行结果
给出运行结果,并分析。
分析:
- 左边为读取的信息,右边为写入的信息
- 需要打开2个窗口,同时运行读和写才能建立连接
- 输入shut down关闭管道
3. 通过该实验产生新的疑问及解答
做完这个实验,我了解到管道这一种基本IPC机制,只作用于有血缘关系的进程之间(局限性)
有这么一些特点:
- 管道是核缓冲区(内核使用环形队列机制)
- 数据从写端流入管道再从读端流出,而且不能逆向流动
- 数据一旦被读走,管道里面就不存在了,不能反复读取