-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpipe_sync.c
More file actions
66 lines (52 loc) · 1.04 KB
/
pipe_sync.c
File metadata and controls
66 lines (52 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
//使用管道同步 思路来自TLPI
/**
* 当管道为空且存在写端口时,管道的读端会被阻塞
* 当管道为空且所有的写端口都被关闭的时候,对管道的读写会出错返回-1
* 使用阻塞来实现同步
*/
int main(int argc, char *argv[])
{
int pfd[2];
int j, dummy;
setbuf(stdout, NULL);
if (pipe(pfd) == -1)
{
perror("pipe");
}
for (j = 0; j < 2; j++)
{
switch (fork())
{
case -1:
perror("fork");
case 0:
if (close(pfd[0]) == -1)
{
perror("close");
}
sleep(j + 1);
printf("Child %d (PID=%ld) closing pipe\n", j,
(long)getpid());
if (close(pfd[1]) == -1)
{
perror("close");
}
_exit(EXIT_SUCCESS);
default:
break;
}
}
if (close(pfd[1]) == -1)
perror("close");
if (read(pfd[0], &dummy, 1) != 0)
perror("parent didn't get EOF");
printf(" Parent ready to go\n");
exit(EXIT_SUCCESS);
}