操作系统第三次实验报告:管道

  • 姓名:吕煜华
  • 学号:201821121046
  • 班级:计算1812

1. 编写程序

在服务器上用Vim编写程序:创建一个命名管道,创建两个进程分别对管道进行读fifo_read.c和写fifo_write.c。给出源代码。

fifo_write.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 {
 10     int fd= open("fifo",O_WRONLY);
 11     if(fd<0) {
 12         printf("open error!\n");
 13         return -1;
 14     }
 15     while(1) {
 16         char buf_w[1024];
 17         printf("write is:"); 
 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 }

 

 

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<fcntl.h>
  7 int main(){
  8     unlink("fifo");
  9     if(mkfifo("fifo",0777)<0) {
 10         printf("creat error!\n");
 11         return -1;
 12     }
 13     int fd= open("fifo", O_RDONLY);
 14     if(fd<0) {
 15         printf("open error!\n");
 16         return -2;
 17     }
 18     char buf_r[1024];
 19     while(1) {
 20         ssize_t size=read(fd, buf_r, sizeof(buf_r)-1);
 21         if(size<0) {
 22             printf("read error!\n");
 23             break;
 24         }else if(size>0) {
 25             printf("read is:%s",buf_r);
 26         }
 27     }
 28    close(fd);
 29    return 0;
 30 }

 

  

2. 分析运行结果

给出运行结果,并分析。

打开两个终端,分别打开fifo_write.c和fifo_read.c,在写的一端将输入写入管道,读的一段从管道中读出数据。

写的过程:

读的过程:

 

 

3. 通过该实验产生新的疑问及解答

通过该实验如果有产生新的疑问,可以写出来,并尝试自己解决问题。

1.要先运行fifo_read.c,再运行fifo_write.c。

因为阻塞的作用。

posted @ 2020-04-18 17:09  Lvyuhua  阅读(202)  评论(0编辑  收藏  举报