操作系统第3次实验报告:管道
- 姓名:徐思婕
- 学号:201821121004
- 班级:计算1811
1. 编写程序
- 在服务器上用Vim编写程序:创建一个命名管道,创建两个进程分别对管道进行读
fifo_read.c和写fifo_write.c:
fifo_read.c:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/stat.h>
int main(){
char * file ="fifo";
//打开管道文件
int fd=open(file,O_RDONLY);
if(fd<0){
perror("open error");
}
printf("open fifo success!\n");
//建立命名管道
umask(0);
int ret=mkfifo(file,0664);
if(ret<0){
if(errno != EEXIST)
perror("mkfifo error");
}
//从管道中读取文件
while(1){
char buf[1024];
ret=read(fd,buf,1023);
if(ret<0){
perror("read error!\n");
}else if(ret==0){
printf("write closed!\n");
return -1;
}
printf("read:%s\n",buf);
}
close(fd);
return 0;
}
fifo_write.c:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/stat.h>
int main(){
char * file="fifo";
//打开管道文件
int fd=open(file,O_WRONLY);
if(fd<0){
perror("open error");
}
printf("open fifo success!\n");
//建立命名管道
umask(0);
int ret=mkfifo(file,0664);
if(ret<0){
if(errno!=EEXIST)
perror("mkfifo error");
}
//从管道中读取文件
while(1){
char buf[1024];
printf("write:");
scanf("%s",buf);
ret=write(fd,buf,strlen(buf));
if(ret<0){
perror("write error!\n");
return -1;
}
}
close(fd);
return 0;
}
2. 分析运行结果
- 给出运行结果,并分析:


打开两个窗口,一个运行fifo_write.c输入,另一个运行fifo_read.c读取并输出。
3. 通过该实验产生新的疑问及解答
- 问:为什么先启动fifo_write.c没有反应,直到启动fifo_read.c后才会输出open fifo success?
答:因为读管道进程在建立管道之后就开始循环地从管道里读出内容,如果没有数据可读,则一直阻塞到写管道进程向管道写入数据。在启动了写管道程序后,读进程能够从管道里读出用户的输入内容。

浙公网安备 33010602011771号