操作系统第3次实验:命名管道

0.个人信息

  • 姓名:王璐璐
  • 学号:201821121037
  • 班级:计算1812

1.编写程序

  •  创建进程对管道进行读 fifo_write.c,代码如下:
 #include <stdio.h>
 #include <stdlib.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <sys/stat.h>
 #include <errno.h>
 #include <string.h>
 int main(){
     int fd,sc;
   char buf[1024];
   //用只写打开fifo文件 if((fd = open("fifo",O_WRONLY)) < 0){ perror("Open fifo failed\n"); exit(1); }
   //循环写入内容 while(1){ printf("Write message: "); gets(buf); sc = write(fd,buf,strlen(buf)+1); if(sc < 0){ perror("Write failed\n"); close(fd); exit(1); } } close(fd); return 0; }

创建进程对管道进行写 fifo_read.c,代码如下:

 #include <stdio.h>
 #include <stdlib.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <sys/stat.h>
 #include <errno.h>
 int main(){
    int fd,rd;
   char buf[1024];
    //创建fifo管道 
   if((mkfifo("fifo",0664) < 0) && errno!=EEXIST){ 
   perror("Create fifo failed\n"); exit(1); 
   }
  //用只读打开fifo文件
     if((fd = open("fifo",O_RDONLY)) < 0){
         perror("Open fifo failed\n");
         exit(1);
     }
  //实时读取fifo文件中的内容
     while(1){
         rd = read(fd,buf,1024);
         if(rd < 0){
             perror("Read error\n");
             exit(1);
         }
         printf("Read message: %s\n", buf);
     }
     close(fd);
     return 0;
 }  

2.分析运行结果

编译成功后,打开两个服务器,在一个服务器上运行fifo_write.c文件,在另一个服务器上运行fifo_read.c文件,实时监控写入fifo文件的内容:

  • 在fifo_write.c中,通过gets()函数读取一整行的字符串
  • 当在fifo_write进程下,没有写任何内容,fifo_read进程处于阻塞状态;当在fifo_write进程中写入一串字符串时,fifo_read进程将实时更新fifo_write进程中写到的内容

3.该实验中产生的问题和解答问题:

  • 问题1:代码int mkfifo(const char* path, mode_t mod);中的mode_t mod是什么意思?
  • 解答1:mode_t mod 是对在设置文本的权限,可以使用数字表示法去修改权限,具体解释可以参考下面的链接
  • 问题2:一开始运行fifo_write.c时,fifo_read.c并没有实时显示输入的字符串
  • 解答2:经多次修改和实验后,发现是在编译的时候出现了问题,使用gcc fifo_write.c -o fifo_write时,只编译了一部分,需要再加一条命令——gcc fifo_write.c

4.参考链接

猜你喜欢

转载自www.cnblogs.com/jmuaia-wll/p/12723494.html