操作系统第3次实验报告:管道

0. 个人信息

  • 姓名  雷坛春
  • 学号  201821121030
  • 班级  计算1811

1. 编写程序

创建一个命名管道,创建两个进程分别对管道进行读和写:

//fifo_write

#include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <signal.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> void handle_sig(int sig) { printf("signal pipe\n"); exit(-1); } int main(int argc, char** argv) { int fd; int ret; char buf[128]; int i = 0; /*处理管道信号*/ signal(SIGPIPE, handle_sig); if(mkfifo("./fifo", 0640) == -1) { if(errno != EEXIST) { perror("mkfifo"); return -1; } } /*只写方式打开管道*/ fd = open("./fifo", O_WRONLY); if(fd == -1) { perror("open"); return -1; } while(1) { scanf("%s",buf); //sprintf(buf, "data %d", i++); /*往管道写数据*/ ret = write(fd, buf, strlen(buf)); printf("write fifo [%d] %s\n", ret, buf); sleep(1); } return 0; }
//fifo_read

#include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <signal.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> int main(int argc, char** argv) { int fd; int ret; char buf[128]; if(mkfifo("./fifo", 0640) == -1) { if(errno != EEXIST) /*如果错误类型是fifo文件已经存在,则继续执行*/ { perror("mkfifo"); return -1; } } /*以只读方式打开管道*/ fd = open("./fifo", O_RDONLY); if(fd == -1) { perror("open"); return -1; } while(1) { memset(buf, 0, sizeof(buf)); /*读管道*/ if((sizeof(buf)-1)) { ret = read(fd, buf, sizeof(buf) - 1); printf("read fifo [%d] : %s\n", ret, buf); } } return 0; }

 

2. 运行结果

1.输入端

 

 

2.输出端

 

 

3. 通过该实验产生问题及解答

posted @ 2020-04-15 11:43  殇墨痕  阅读(196)  评论(0编辑  收藏  举报