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

  • 姓名:倪晓东
  • 学号:201821121020
  • 班级:计算1811

1. 编写程序

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

pipes.c创建管道

 1 #include<stdio.h>
  2 #include<sys/types.h>
  3 #include<sys/stat.h>
  4 int main(){
  5     int new=mkfifo("fifo",0777);
  6     if(new<0){
  7         printf("创建管道失败!\n");
  8         return -1;
  9     }
 10     printf("创建成功!\n");
 11     return 0;
 12 }

fifo_read.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<fcntl.h>
  7 #define SIZE 1024
  8 int main(){
  9      int fd = open("fifo",O_RDONLY);
 10      if(fd<0){
 11          printf("Fail to open!\n");
 12          return -1;
 13      }
 14          printf("strating read!\n");
 15          while(1){
 16          char buf[SIZE]={0};
 17          int ret=read(fd,buf,SIZE);
 18          if(ret>0)
 19          printf("reading:%s\n",buf);
 20      }
 21      close(fd);
 22      return 0;
 23 }

 

fifo_write.c写入程序:

1 #include<stdio.h>
  2 #include<unistd.h>
  3 #include<sys/types.h>
  4 #include<string.h>
  5 #include<sys/stat.h>
  6 #include<fcntl.h>
  7 #define SIZE 1024
  8 int main(){
  9     int fd=open("fifo",O_WRONLY);
 10     if(fd<0){
 11         printf("fail to open!\n");
 12         return -1;
 13     }
 14     else{
 15         printf("Start write!\n");
 16         while(1){
 17             char buf[SIZE];
 18             printf("write:");
 19             scanf("%s",buf);
 20             write(fd,buf,SIZE);
 21             printf("输入成功!\n");
 22         }}
 23         close(fd);
 24      return 0;
 25
 26 }

 

 

2. 分析运行结果

执行pipes.c创建命名管道:

 

 因为之前创建过所以创建失败,管道正在运行。

再开一个窗口执行fifo_read,另一个执行fifo_write:

 

 

 

分析:通过创建管道将两个进程连接,再写进程里面写入数据,读进程可以通过管道读取数据,相当于写进程再写入的同时将数据通过管道送到读进程里,具有实时性。

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

创建管道后,如果只读,或者只写,会怎样?

 从执行结果看:当只读或者只写方式打开命名管道,会进入阻塞状态,因为里面的open函数进入阻塞等待状态,直到有写进程运行才打开命名管道

通过网上了解打开命名管道的方式有:

(1)只读且阻塞方式 
        open(const char *pathname, O_RDONLY);
(2)只读且非阻塞方式 
        open(const char *pathname, O_RDONLY | O_NONBLOCK);
(3)只写且阻塞方式 
        open(const char *pathname, O_WRONLY);
(4)只写且非阻塞方式 
        open(const char *pathname, O_WRONLY | O_NONBLOCK);

我在读写程序里面所用的方式为只读且阻塞方式和只写且阻塞方式 。

注意到在课堂派互动上如果有同学在互动上填写答案,即时没有提交,老师也能在后台看到数据,是否是同样原理?

posted @ 2020-04-17 16:49  Linial  阅读(202)  评论(0编辑  收藏  举报