• 姓名 陈悦凯
  • 学号 201821121011
  • 班级 计算1811

1. 编写程序

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

fifo_read.c

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <errno.h>
  4 #include <string.h>
  5 #include <unistd.h>
  6 #include <fcntl.h>
  7
  8 int main()
  9 {
 10     int r = open("fifo",O_RDONLY);
 11     if(r<0)
 12     {
 13         printf("no 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("read success,exit\n");
 25                 break;
 26             }
 27             printf("the read message is:%s\n",string);
 28         }
 29         close(r);
 30         return 0;
 31     }
 32
 33 }

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
  8 int main()
  9 {
 10     int w=open("fifo",O_WRONLY);
 11     if(w<0)
 12     {
 13         printf("can not open fifo\n");
 14         return -1;
 15     }
 16     else
 17     {
 18         printf("begin write,please enter something,input stop to exit.\n");
 19         while(1)
 20         {
 21             printf("enter:");
 22             char string[100];
 23             scanf("%s",string);
 24             if(strcmp(string,"stop")==0)
 25             {
 26                 break;
 27                 printf("out!\n");
 28             }
 29             write(w,string,100);
 30             printf("out put\n");
 31         }
 32
 33     }
 34     close(w);
 35     return 0;
 36 }

pipe.c

  1 #include<stdio.h>
  2 #include<sys/types.h>
  3 #include<sys/stat.h>
  4
  5 int main()
  6 {
  7     int pipe = mkfifo("fifo",0777);
  8     if(pipe<0)
  9     {
 10         printf("create pipe filed\n");
 11         close(fifo);
 12         return -1;
 13     }
 14     printf("create pipe success\n");
 15     return 0;
 16 }

2. 分析运行结果

 

 

 

 通过pipe文件创建了一个管道fifo,通过fifo,write文件和read文件可以进行信息交换,运行read后再运行write,在write下输入东西会吧数据传输到read

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

创建过一次管道后,再次创建会提示错误,可以用rm指令移除创建好的管道

mkfifo("fifo",0777);
mkfifo()会依参数pathname建立特殊的FIFO文件,该文件必须不存在,而参数mode为该文件的权限(mode%~umask),因此 umask值也会影响到FIFO文件的权限。Mkfifo()建立的FIFO文件其他进程都可以用读写一般文件的方式存取。当使用open()来打开 FIFO文件时,O_NONBLOCK旗标会有影响
posted on 2020-04-18 14:05  chenyuekai  阅读(164)  评论(0编辑  收藏  举报