- 姓名:肖斯凯
- 学号:201821121015
- 班级:计算1811
1. 编写程序
在服务器上用Vim编写程序:创建一个命名管道,创建两个进程分别对管道进行读fifo_read.c和写fifo_write.c。给出源代码。
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 f=open("fifo",O_WRONLY);
10 if(f<0){
11 printf("failure\n");
12 return -1;
13 }
14 while(1){
15 char c[20];
16 printf("the other side is reading.");
17 fflush(stdout);
18 ssize_t size=read(0,c,sizeof(c)-1);
19 if(c[0]=='0'){
20 printf("exit successful\n");
21 write(f,c,strlen(c));
22 break;
23 }else{
24 c[size]=0;
25 write(f,c,strlen(c));
26 }
27 }
28 close(f);
29 return 0;
30 }
fifo_read.c
1 #include <stdio.h>
2 #include<errno.h>
3 #include <sys/stat.h>
4 #include <sys/types.h>
5 #include <stdlib.h>
6 #include <fcntl.h>
7 #include <unistd.h>
8 int main(){
9 unlink("fifo");
10 if(mkfifo("fifo",0777)==-1){
11 if(errno==EEXIST)
12 printf("this exist\n");
13 else{
14 printf("failure\n");
15 return -1;
16 }
17 }
18 int f=open("fifo",O_RDONLY);
19 if(f<0){
20 printf("fail!\n");
21 return -1;
22 }
23 char c[20];
24 while(1){
25 printf("the other side is writing.\n");
26 ssize_t size=read(f,c,sizeof(c)-1);
27 if(size<0){
28 printf("error!\n");
29 break;
30 }else if(size>0){
31 if(c[0]=='0')
32 break;
33 else{
34 c[size]=0;
35 printf("the content is:%s",c);
36 }
37 }
38 }
39 close(f);
40 return 0;
41 }
2. 分析运行结果
打开两个终端运行程序之后,write方输入,read方即可读到并输出,当write写入0时,信息还是会传过去,然后write方退出程序,read方收到判断出字符为0时也自动退出程序,且不输出信息

3. 通过该实验产生新的疑问及解答
read函数的作用是什么:
例如:
read(f,c,a)
read()会把参数f 所指的文件传送a个字节到c指针所指的内存中。