操作系统第3次实验报告:管道
- 姓名:黄财泽
- 学号:201821121014
- 班级:计算1811
一、实验目的
掌握进程间通信管道的编程。
二、实验内容
- 在服务器上用VIM编写一个程序:创建一个命名管道,创建两个进程分别对管道进行读
fifo_read.c
和写fifo_write.c
。给出源代码 - 给出运行结果,并分析
三、实验报告
1. 编写程序
在服务器上用Vim编写程序:创建一个命名管道,创建两个进程分别对管道进行读fifo_read.c
和写fifo_write.c
。
fifo_read程序:
1 #include<stdio.h> 2 #include<unistd.h> 3 #include<errno.h> 4 #include<fcntl.h> 5 #include<string.h> 6 #include<sys/types.h> 7 #include<sys/stat.h> 8 #include<stdlib.h> 9 10 int main() 11 { 12 char *file = "./myfifo.fifo"; 13 umask(0); 14 if(mkfifo(file , 0664)<0){ 15 if(errno == EEXIST){ 16 printf("fifo exist!\n"); 17 } 18 else { 19 perror("mkfifo"); 20 return -1; 21 } 22 23 } 24 int fd = open(file,O_RDONLY); 25 if(fd<0){ 26 perror("open error"); 27 return -1; 28 } 29 printf("open fifo success!\n"); 30 while(1){ 31 char buff[1024]; 32 memset(buff, 0x00,1024); 33 int ret = read(fd,buff,1024); 34 if(ret > 0) 35 printf("peer say: %s\n",buff); 36 37 } 38 close(fd); 39 return 0; 40 41 42 }
fifo_write程序:
1 #include<sys/types.h> 2 #include<sys/stat.h> 3 #include<errno.h> 4 #include<fcntl.h> 5 #include<stdio.h> 6 #include<stdlib.h> 7 #include<string.h> 8 #include<unistd.h> 9 int main(){ 10 char *file = "./myfifo.fifo"; 11 umask(0); 12 if(mkfifo(file, 0664)<0){ 13 if(errno == EEXIST) 14 printf("fifo exist!\n"); 15 }else 16 { 17 perror("mkfifo"); 18 return -1; 19 } 20 int fd = open(file, O_WRONLY); 21 if(fd < 0){ 22 perror("open error"); 23 return -1; 24 } 25 printf("oprn fifo success!"); 26 while(1){ 27 printf("input :"); 28 fflush(stdout); 29 char buff[1024] = {0}; 30 scanf("%s" , buff); 31 write(fd,buff,strlen(buff)); 32 33 } 34 close(fd); 35 return 0; 36 37 }
2. 分析运行结果
运行结果:
显示已连接成功,
右边输入,写入管道中,左边回经过1s的延迟读出。
管道模式:
O_RDONLY:读管道。
O_WRONLY:写管道。
O_RDWR:读写管道。
O_NONBLOCK:非阻塞。
O_CREAT:如果该文件不存在,就创建一个新的文件,并使用第3个参数为其设置权限。
O_EXCL:测试文件是否存在。
3. 通过该实验产生新的疑问及解答
疑惑:是否可以用命令创建一个fifo?
解答:可以同通过命令 mkfifo filename.fifo 创建管道,当然也可以在程序中创建。
使用 int mkfifo(const char *filename, mode_t mode);