操作系统第3次实验报告:管道
2020-04-17 20:17 Wangpj 阅读(284) 评论(0) 编辑 收藏 举报姓名:王丕杰
班级:计算1812
学号:201821121052
一、实验目的
掌握进程间通信管道的编程。
二、实验内容
- 在服务器上用VIM编写一个程序:创建一个命名管道,创建两个进程分别对管道进行读
fifo_read.c
和写fifo_write.c
。给出源代码 - 给出运行结果,并分析
三、实验报告
1. 编写程序
在服务器上用Vim编写程序:创建一个命名管道,创建两个进程分别对管道进行读fifo_read.c
和写fifo_write.c
。给出源代码。
fifo_read.c
1 #include<stdio.h> 2 #include<unistd.h> 3 #include<sys/types.h> 4 #include<sys/stat.h> 5 #include<stdlib.h> 6 #include<string.h> 7 #include<fcntl.h> 8 int main(){ 9 unlink("fifo"); 10 if(mkfifo("fifo",0777)<0){ 11 printf("creat error\n"); 12 return -1; 13 } 14 int fd= open("fifo",O_RDONLY); 15 if(fd<0){ 16 printf("error!"); 17 return -2; 18 } 19 char buf_r[1024]; 20 while(1){ 21 ssize_t size=read(fd,buf_r,sizeof(buf_r)-1); 22 if(size<0){ 23 printf("read error!\n"); 24 break; 25 }else if(size>0){ 26 buf_r[size]=0; 27 printf("read:%s\n",buf_r); 28 }else{ 29 printf("exit"); 30 } 31 } 32 close(fd); 33 return 0; 34 }
fifo_write.c
1 #include<stdio.h> 2 #include<unistd.h> 3 #include<sys/types.h> 4 #include<sys/stat.h> 5 #include<string.h> 6 #include<stdlib.h> 7 #include<fcntl.h> 8 int main() 9 { 10 int fd = open("fifo",O_WRONLY); 11 if(fd<0){ 12 printf("error!"); 13 return -1; 14 } 15 while(1){ 16 char buf_w[1024]; 17 printf("write:"); 18 fflush(stdout); 19 ssize_t size= read(0,buf_w,sizeof(buf_w)-1); 20 if(size<=0){ 21 printf("write error!\n"); 22 break; 23 }else if(size>0){ 24 buf_w[size]=0; 25 write(fd,buf_w,strlen(buf_w)); 26 } 27 } 28 close(fd); 29 return 0; 30 }
2. 分析运行结果
打开两个窗口,分别打开fifo_read.c和fifo_write.c,一边写入数据,一边输出。
运行结果如下:
3. 通过该实验产生新的疑问及解答
同时利用两个窗口打开读和写的文件时,两个窗口均无反应。
解决办法:打开文件时注意打开顺序,在打开运行fifo_write之前,必须先打开fifo_read,否则无反应,这与阻塞的作用有关。