操作系统第3次实验报告:管道
- 姓名:蒋浩天
- 学号:201821121024
- 班级:计算1811
1. 编写程序
在服务器上用Vim编写程序:创建一个命名管道,创建两个进程分别对管道进行读fifo_read.c
和写fifo_write.c
。给出源代码。
fifo_read.c
1 #include<unistd.h> 2 #include<errno.h> 3 #include<stdio.h> 4 #include<stdlib.h> 5 #include<sys/stat.h> 6 #include<sys/types.h> 7 #include<fcntl.h> 8 9 int main() 10 { //创建名为fifo的管道,0777表示权限为rwx 11 int mkf=mkfifo("fifo",0777); 12 if(mkf<0){ 13 printf("Failed to create fifo!\n"); 14 return -1; 15 } 16 //打开管道,O_RDONLY表示只读 17 int fr=open("fifo",O_RDONLY); 18 if(fr<0){ 19 printf("Failed to open fifo!\n"); 20 return -1; 21 } 22 else{ 23 printf("Start reading!\n"); 24 while(1){ 25 char buffer[100]={0}; 26 int size=read(fr,buffer,100); 27 if(size>0){ 28 printf("Read content:%s\n",buffer); 29 } 30 } 31 } 32 close(fr); 33 return 0; 34 }
fifo_write.c
1 #include<unistd.h> 2 #include<errno.h> 3 #include<stdio.h> 4 #include<stdlib.h> 5 #include<sys/stat.h> 6 #include<sys/types.h> 7 #include<fcntl.h> 8 9 int main() 10 { //打开管道,O_WRONLY表示只写 11 int fw=open("fifo",O_WRONLY); 12 if(fw<0){ 13 printf("Failed to open fifo!\n"); 14 return -1; 15 } 16 else{ 17 printf("Start writing!\n"); 18 while(1){ 19 printf("write:"); 20 char buffer[100]; 21 scanf("%s",buffer); 22 int size=write(fw,buffer,100); 23 if(size<0){ 24 printf("Error!\n"); 25 } 26 else{//显示输入的内容,用作验证 27 printf("Write content:%s\n",buffer); 28 } 29 } 30 } 31 close(fw); 32 return 0; 33 }
2. 分析运行结果
结果:
分析:1.运行时要先运行read程序,因为创建fifo管道的指令在fifo_read.c的代码中,如果先运行write程序,会提示“failed to open fifo"。
2.运行完read程序后,该目录下会生成一个名为“fifo”的文件,此时,程序没有任何输出,只有当write程序运行时,read程序的“Starting reading!"字样才会输出。
3.如果运行一次结束后,想要再次运行,需要先删除fifo文件,不然在运行read程序时会因为无法创建fifo管道而终止运行。
4.如果输入的字符串之间有空格,字符串会被分开显示:
3. 通过该实验产生新的疑问及解答
在前期尝试的过程中,发现如果输入的字符串之间有空格,字符串会被分开显示。通过在代码中添加”显示输入内容“作为检测,发现了因为空格,让字符串分开进入管道,分开显示。write content的内容和read content的内容是同步的。
我写的两个读写程序都是死循环,想要停止程序只能通过ctrl+c。想要优化它,可以在输入某字符时,表示结束程序。可以通过判断指令,当输入特定字符时跳出循环,结束程序。
mode: O_RDONLY, O_WRONLY, O_RDWR 中的每个模式代表什么意思。经过查找,发现O_RDONLY就是read only 表示只读,O_WRONLY就是write only 表示只写,O_RDWR就是read write 表示可读可写。