-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultiple-pipes.c
147 lines (136 loc) · 3.46 KB
/
multiple-pipes.c
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
three processes
process 1 creates a x, sends to the next which adds 5
sends to the next which adds 5 again
sends it back to original
________________
| |
| x |
|_______________|
| |
| |
_______|_______ ______|________
| | | |
| x+5 | | x+5 |
|______________| |______________|
so we need three pipes, 6 file descriptors in the main process
these are inherited by the child processes
so 6*3 = 18 file descriptors
fd[3][2]
fd[0][1]
________________ fd[2][0]
| |
| x |
|_______________|
| |
fd[0][0] | | fd[2][1]
_______|_______ ______|________
| | | |
| x+5 | | x+5 |
|______________|_|______________|
fd[1][1] fd[1][0]
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int fd[3][2];
int i;
for (i = 0; i < 3; i++)
{
if (pipe(fd[i]) < 0)
{
printf("failed to create pipe\n");
return 1;
}
}
int x;
printf("Input number: ");
scanf("%d", &x);
if (write(fd[0][1], &x, sizeof(int)) < 0)
{
printf("write failed\n");
return 8;
}
int pid1 = fork();
if (pid1 < 0)
{
printf("failed to fork\n");
return 2;
}
if (pid1 == 0)
{
// child process 1
close(fd[0][1]);
close(fd[1][0]);
close(fd[2][0]);
close(fd[2][1]);
int x;
if (read(fd[0][0], &x, sizeof(int)) < 0)
{
printf("read failed\n");
return 3;
}
// printf("%d\n", x);
x += 5;
// printf("%d\n", x);
if (write(fd[1][1], &x, sizeof(int)) < 0)
{
printf("write failed\n");
return 4;
}
close(fd[0][0]);
close(fd[1][1]);
return 0;
}
int pid2 = fork();
if (pid2 < 0)
{
printf("failed to fork\n");
return 5;
}
if (pid2 == 0)
{
// child process 2
close(fd[0][1]);
close(fd[2][0]);
close(fd[0][0]);
close(fd[1][1]);
int x;
if (read(fd[1][0], &x, sizeof(int)) < 0)
{
printf("read failed\n");
return 6;
}
// printf("%d\n", x);
x += 5;
// printf("%d\n", x);
if (write(fd[2][1], &x, sizeof(int)) < 0)
{
printf("write failed\n");
return 7;
}
close(fd[1][0]);
close(fd[2][1]);
return 0;
}
// parent process
if (read(fd[2][0], &x, sizeof(int)) < 0)
{
printf("read failed\n");
return 9;
}
close(fd[0][0]);
close(fd[1][1]);
close(fd[2][1]);
close(fd[1][0]);
close(fd[0][1]);
close(fd[2][0]);
printf("Result is %d\n", x);
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
return 0;
}