才半页

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  • 李微微
  • 201821121001
  • 计算1811

1. 编写程序

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

fifo_read.c:
1 #include <stdio.h> 2 #include <sys/stat.h> 3 #include <sys/types.h> 4 #include <stdlib.h> 5 #include <fcntl.h> 6 #include <unistd.h> 7 int main(){ 8 unlink("FIFO"); 9 if(mkfifo("FIFO",0777)<0){ //创建管道 10 printf("Can't create!\n"); 11 return -1; 12 } 13 int flag=open("FIFO",O_RDONLY); //阻塞方式 14 if(flag<0){ 15 printf("Open error!\n"); 16 return -2; 17 } 18 char buf_r[200]; 19 while(1){ 20 printf("Waiting...\n"); 21 ssize_t size=read(flag,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 from FIFO:%s",buf_r); 28 }else{ 29 printf("Exit!"); 30 } 31 } 32 close(flag); 33 return 0; 34 }
fifo_write.c
  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #include <sys/stat.h>
  5 #include <sys/types.h>
  6 #include <fcntl.h>
  7 #include <unistd.h>
  8 int main(){
  9     int flag=open("FIFO",O_WRONLY);    //阻塞方式
 10     if(flag<0){
 11         printf("Open error!\n");
 12         return -1;
 13     }
 14     while(1){
 15         char buf_w[200];
 16         printf("Please write:");
 17         fflush(stdout);
 18         ssize_t size=read(0,buf_w,sizeof(buf_w)-1);
 19         if(size<=0){
 20             printf("read error!\n");
 21             break;
 22         }else if(size>0){
 23             buf_w[size]=0;
 24             write(flag,buf_w,strlen(buf_w));
 25         }
 26     }
 27     close(flag);
 28     return 0;
 29 }

2. 分析运行结果

运行结果:

(1)运行两个窗口,一个运行fifo_read,另一个运行fifo_write:

            

 

 

(2)当在fifo_write中输入信息,可在fifo_read中显示:

          

 

(3)可重复输入:

 

 

         

 

 

分析运行结果:
两个进程,通过一个管道FIFO进行通信交流。必须先运行fifo_read.c,创建管道后,运行fifo_write才有结果。

 

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

(1)疑问:我先是使用mkfifo("FIFO",O_CREAT)语句创建管道,但在两个进程通信一次之后,再次运行fifo_read就提示“Can't create!”。

         解决:通过上网搜索,得知mkfifo命令无法使用时,可以使用unlink("FIFO"); mkfifo("FIFO",0777)创建命名管道。

         (https://blog.csdn.net/l344155279/article/details/6721189)

(2)在打开运行fifo_write之前,必须已执行过fifo_read,否则无效果,与阻塞的作用有关。

(3)疑问:当在VIM中不小心习惯性Ctrl+s之后,会挂死,按任何键都毫无反应。

         解决:通过网上搜索得知,Ctrl+s是“阻断向终端输出”,按Ctrl+q可解决。(https://blog.csdn.net/ycjnx/article/details/76014455)

                    但再次启动后要删除产生的.swp文件。

posted on 2020-04-15 16:49  才半页  阅读(180)  评论(0编辑  收藏  举报