匿名管道的4种情况:
1.如果所有指向管道写端的文件描述符都关闭了(管道写端的引用计数等于0),而仍有进程从管道的读端读取数据,那么管道中剩余的数据都被读取后,再次read会返回0,就像读到文件末尾一样。
1 #include <sys/types.h>
2 #include <sys/wait.h>
3 #include <unistd.h>
4 #include <stdio.h>
5 #include <string.h>
6 int main()
7 {
8 ssize_t n;
9 int i=0;
10 int fd[2]={0, 0 };
11 char buf[1024];
12 if(pipe(fd)<0)
13 {
14 perror("pipe");
15 return 1;
16 }
17 pid_t pid = fork();
18 if(pid < 0)
19 {
20 perror("fork");
21 return 2;
22 }
23 if(pid == 0)
24 {
25 close(fd[0]);//--->write
26 const char* arr = "hello linux!\n";
27 while(i<10)
28 {
29 write(fd[1], arr, strlen(arr));
30 sleep(1);
31 i++;
32 }
33 close(fd[1]);
34 }
35 else
36 {
37 close(fd[1]);//---->read
38 i=0;
39 while(i<20)
40 {
41 memset(buf, '\0', sizeof(buf));
42 n = read(fd[0], buf, sizeof(buf));
43 printf("client->father#%s, read() = %d\n", buf, n);
44 i++;
45 }
46 }
47 return 0;
48 }
2.如果有指向管道写端的文件描述符没关闭(管道写端的引用计数大于1),而持有管道写端的进程也没有向管道中写数据,那么管道中剩余的数据都被读取后,再次read会阻塞,直到管道中。
代码:
不要关闭父进程的写端fd[1];
已经阻塞。
3.如果所有指向管道读端的文件描述符都关闭了,这时有进程向管道的写端write,那么 该进程就会收到信号SIGPIPE,通常会导致进程异常终止。
close(fd[0]);
close(fd[1]);
read() == -1;
4.如果有指向管道读端的文件描述符没关闭,而持有管道读端的进程也没有从管道中读取数据,这时有进程向管道写端写数据,那么在管道写端被写满时再次write会阻塞,直到管道中有空位置才写入数据并返回。