命名管道——进程通信案例

该案例是实现两个进程之间使用命名管道进行通信。

进程1:fifo01.c

 1 #include<unistd.h>
 2 #include<sys/types.h>
 3 #include<sys/stat.h>
 4 #include<stdio.h>
 5 #include<stdlib.h>
 6 #include<fcntl.h>
 7 #include<string.h>
 8 #include<errno.h>
 9 int main(int argc, char const *argv[])
10 {
11     if(mkfifo("myfifo1",0664) == -1)
12     {
13         if(errno != EEXIST)
14         {
15             perror("Fail to mkfifo1");
16             exit(1);
17         }
18     }
19     if(mkfifo("myfifo2",0664) == -1)
20     {
21         if(errno != EEXIST)
22         {
23             perror("Fail to mkfifo1");
24             exit(1);
25         }
26     }
27     int fd_w = open("myfifo1",O_WRONLY);
28     if(fd_w == -1)
29     {
30         perror("Fail to open myfifo1");
31         exit(1);
32     }
33     int fd_r = open("myfifo2",O_RDONLY);
34     if(fd_r == -1)
35     {
36         perror("Fail to open myfifo2");
37         exit(1);
38     }
39     pid_t pid;
40     pid = fork();
41     if(pid < 0)
42     {
43         perror("fail to fork");
44         exit(1);
45     }
46     else if(pid == 0)
47     {
48         while (1)
49         {
50             char buf[128] = "";
51             fgets(buf,sizeof(buf),stdin);
52             buf[strlen(buf) - 1] = '