操作系统第3次实验报告:管道
- 姓名 邹文兵
- 学号 201821121028
- 班级 计算1811
1. 编写程序
在服务器上用Vim编写程序:创建一个命名管道,创建两个进程分别对管道进行读fifo_read.c
和写fifo_write.c
。给出源代码。
1、创建命名管道代码 fifo_make.c
1 #include <stdio.h> 2 #include <sys/types.h> 3 #include <stdlib.h> 4 #include <unistd.h> 5 #include <string.h> 6 #include <sys/stat.h> 7 #include <fcntl.h> 8 9 char writebuffer[200]; 10 11 int main() 12 { 13 int m = mkfifo("MyFifo",0777); 14 if(m<0){ //创建命名管道 15 printf("mkfifo fails.\n"); 16 return -1; 17 } 18 printf("mkfifo success.\n"); 19 return 0; 20 } 21
2、对管道进行读 fifo_read.c
1 #include <stdio.h> 2 #include <unistd.h> 3 #include <sys/types.h> 4 #include <string.h> 5 #include <stdlib.h> 6 #include <sys/stat.h> 7 #include <fcntl.h> 8 9 char readbuffer[200]; 10 11 int main() 12 { 13 int r = open("MyFifo",O_RDONLY);//打开命名管道 14 if(r<0) 15 { 16 printf("Fail to open pipe.\n"); 17 return -1; 18 } 19 while(1){ 20 int t=read(r,readbuffer,200);//读取管道 21 if(t<0) 22 { 23 printf("Fail to read fifo.\n"); 24 return -1; 25 } 26 printf("Read string:%s\n",readbuffer); 27 } 28 close(r); //关闭管道 29 return 0; 30 }
3、对管道进行写 fifo_write.c
1 #include <stdio.h> 2 #include <sys/types.h> 3 #include <stdlib.h> 4 #include <unistd.h> 5 #include <string.h> 6 #include <sys/stat.h> 7 #include <fcntl.h> 8 9 char writebuffer[200]; 10 11 int main() 12 { 13 int w = open("MyFifo",O_WRONLY);//打开命名管道 14 if(w<0){ 15 printf("Fail to open fifo.\n"); 16 return -1; 17 } 18 while(1) 19 { 20 printf("请输入写入管道的内容:"); 21 scanf("%s",writebuffer); 22 int t= write(w,writebuffer,(strlen(writebuffer)+1));//写入管道 23 24 if(t<0){ 25 printf("Fail write into fifo.\n"); 26 return -1; 27 } 28 } 29 close(w);//关闭管道 30 31 return 0; 32 }
2. 分析运行结果
给出运行结果,并分析。
1、创建命名管道fifo_make.c编译运行后结果为mkfifo success.即创建管道成功。
2、刚开始对管道进行读 fifo_read.c 编译运行时并无任何反应,等对管道进行写 fifo_write.c编译运行后,在窗口输入对应地内容后,fifo_read窗口才输出对应数据,证明此时管道已发挥作用。
3. 通过该实验产生新的疑问及解答
通过该实验如果有产生新的疑问,可以写出来,并尝试自己解决问题。
产生的问题:刚开始创建命名管道与对管道写的代码写在同一个程序fifo_write.c中,导致该程序只有在开始时会创建管道成功,值后再测试时发现创建管道失败。
产生原因及解决方法:这是因为管道创建好后已经存在,再次进行创建时会失败,导致之后也无法再进行写,只需将写与创建分开写在两个程序,并且创建程序只需运行一次即可。