操作系统第3次实验报告:管道
- 姓名:祁翌炀
- 学号:201821121019
- 班级:计算1811
1. 编写程序
在服务器上用Vim编写程序:创建一个命名管道,创建两个进程分别对管道进行读fifo_read.c
和写fifo_write.c
。给出源代码。
创建一个命名管道 pipe.c
1 #include <stdio.h> 2 #include <sys/types.h> 3 #include <sys/stat.h> 4 5 int main() 6 { 7 int guandao=mkfifo("fifo",0777); 8 if(guandao<0) 9 { 10 printf("创建管道失败!\n"); 11 return -1; 12 } 13 printf("创建管道成功\n"); 14 return 0; 15 } ~
创建 fifo_write.c 读入的程序
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <signal.h> 4 #include <unistd.h> 5 #include <fcntl.h> 6 #include <string.h> 7 int main() 8 { 9 int w=open("fifo",O_WRONLY); 10 if(w<0) 11 { 12 printf("无法打开fifo!\n"); 13 return -1; 14 } 15 else 16 { 17 printf("开始写入,请输入数据,退出请输入stop\n"); 18 while(1) 19 { 20 printf("请输入:"); 21 char string[100]; 22 scanf("%s",string); 23 if(strcmp(string,"stop")==0) 24 { 25 break; 26 printf("退出\n"); 27 } 28 write(w,string,100); 29 printf("输入成功!\n"); 30 31 } 32 } 33 close(w); 34 return 0; 35 }
创建 fifo_read 读取的程序
#include <stdio.h> 2 #include <stdlib.h> 3 #include <errno.h> 4 #include <fcntl.h> 5 #include <string.h> 6 #include <unistd.h> 7 8 int main() 9 { 10 int r=open("fifo",O_RDONLY); 11 if(r<0) 12 { 13 printf("未找到fifo文件\n"); 14 return -1; 15 } 16 else 17 { 18 while(1) 19 { 20 char string[100]={0}; 21 int size=read(r,string,100); 22 if(size==0) 23 { 24 printf("读取完毕,退出\n"); 25 break; 26 } 27 printf("此次读取的数据为:%s\n",string); 28 } 29 } 30 close(r); 31 return 0; 32 }
2. 分析运行结果
运行 pipe
第一次创建成功,第二次因为已经存在,所以创建失败。所以证明已经创建成功,并且ls也能看到fifo被创建
此时管道正在被运行,现在打开第二个账号
一号窗口打开fifo.write 二号窗口打开fifo.read
现在开始输入
要结束时候输入stop
这里因为我按错了一个键,导致说按退格键的时候只会退半个字,所以会多打一个字出来,结果输出多了一个“是” 其他结果无误
如果先打开fifo_read 再打开 fifo_write
也可以运行,他就是一种连接状态,你只要上线了,同时都在线就可以传输数据了。
但是如果write先掉线,read也会显示退出,如果是read掉线,write不会掉线。
所以write类似主机端口,进行对于下面的链接的数据传输。
3. 通过该实验产生新的疑问及解答
一开始我上课也听得云里雾里的,对于管道的认知只知道“通讯” 并没有进一步的了解。
后面在这次实验的时候,我明白了更一点点的东西。很多东西就是这个管道的衍生物,类似qq聊天,msn
疑惑:在写代码的时候,发现这整个的读取和存取的规则和c语言中的fprintf()
fscanf特别像,就是创建文件存储和读取文件,fwrite fread和这个的函数格式也特别像,我就翻了原来的一些
关于文件读取和读写的内容进行对比。发现这个就多了一个创建管道的过程,我的理解是实质上
类似局域网的连接。