操作系统第3次实验报告:管道
姓名:蔡婷婷 学号:201821121003 班级:计算1811
1. 编写程序
在服务器上用Vim编写程序:创建一个命名管道,创建两个进程分别对管道进行读fifo_read.c和写fifo_write.c。给出源代码。
fifo_read.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <fcntl.h>
4 #include <string.h>
5 #include <errno.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8
9 int main(){
10 char *file= "fifo";
11 umask(0);
12 //建立命名管道
13 if(mkfifo(file,0664)<0){
14 if(errno!=EEXIST)
15 perror("mkfifo error!!\n");
16 }
17 //打开管道文件
18 int fd=open(file,O_RDONLY);
19 if(fd<0){
20 perror("open error");
21 }
22 printf("open fifo success!!\n");
23 while(1){
24 char buff[1024]={0};
25 int ret=read(fd,buff,sizeof(buff));
26 if(ret>0){
27 printf("read:%s\n",buff);
28 }
29 else if(ret<0){
30 perror("read error!!\n");
31 }
32 else if(ret==0){
33 printf("write closed!!\n");
34 return -1;
35 }
36 }
37 close(fd);
38 return 0;
39 }
Fifo_write.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <fcntl.h>
4 #include <string.h>
5 #include <errno.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8
9 int main(){
10 char *file="fifo";
11 umask(0);
12 //建立命名管道
13 if(mkfifo(file,0664)<0){
14 if(errno!=EEXIST)
15 perror("mkfifo error!!\n");
16 }
17 //打开管道文件
18 int fd=open(file,O_WRONLY);
19 if(fd<0){
20 perror("open error");
21 }
22 printf("open fifo success!!\n");
23 while(1){
24 char buff[1024];
25 printf("write:");
26 scanf("%s",buff);
27 int ret=write(fd,buff,strlen(buff));
28 if(ret<0){
29 perror("write error!!\n");
30 return -1;
31 }
32 }
33 close(fd);
34 return 0;
35 }
2. 分析运行结果
打开两个窗口,其中一个窗口运行fifo_read.c,另一个窗口运行fifo_write.c并输入,此时fifo_write.c中输入的内容会被fifo_read.c读出。
运行结果:
第一个窗口
第二个窗口
3. 通过该实验产生新的疑问及解答
(1)问题:刚开始fifo_read.c读出的内容与fifo_read.c写入的不一致,如下图
解决:发现fifo_read.c中的代码有些错误:
改为后就解决问题了。