-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex11-10.c
More file actions
84 lines (74 loc) · 2.1 KB
/
ex11-10.c
File metadata and controls
84 lines (74 loc) · 2.1 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#define MSGSIZE 16
void parent(int [1][1]);
int child(int []);
void onerror(char* msg) {
printf("%s error", msg);
exit(1);
}
int main() {
int p1[2], p2[2];
char msg[MSGSIZE];
int i;
pid_t pid1, pid2;
fd_set initset, newset;
pid1 = pid2 = 0;
if (pipe(p1) == -1)
onerror("fail to call pipe() #1\n");
if (pipe(p2) == -1)
onerror("fail to call pipe() #2\n");
if ((pid1 = fork()) == -1)
onerror("fail to call fork() #1\n");
if ((pid2 = fork()) == -1)
onerror("fail to call fork() #2\n");
if (pid1 > 0 && pid2 > 0) {
printf("parent: %d\n", getpid());
close(p1[1]);
close(p2[1]);
FD_ZERO(&initset);
FD_SET(p1[0], &initset);
FD_SET(p2[0], &initset);
newset = initset;
while (select(p2[0] + 1, &newset, NULL, NULL, NULL) > 0) {
if (FD_ISSET(p1[0], &newset))
if(read(p1[0], msg, MSGSIZE) > 0)
printf("[parent] %s from child1\n", msg);
if(FD_ISSET(p2[0], &newset))
if(read(p2[0], msg, MSGSIZE) > 0)
printf("[parent] %s from child2\n", msg);
newset = initset;
}
}
else if(pid1 == 0 && pid2 == 0) {
printf("child1: %d\n", getpid());
close(p1[0]);
close(p2[0]);
close(p2[1]);
for (i = 0; i < 3; i++) {
sleep((i + 1) % 4);
printf("child1: send message %d\n", i);
write(p1[1], "i'm child1", MSGSIZE);
}
printf("child1: bye!\n");
exit(0);
}
else if(pid1 > 0 && pid2 == 0) {
printf("child2: %d\n", getpid());
close(p1[0]); close(p1[1]); close(p2[0]);
for(i=0;i<3;i++){
sleep((i + 3) % 4);
printf("child2: send message %d\n", i);
write(p2[1], "i'm child2", MSGSIZE);
}
printf("child2: bye!\n");
exit(0);
}
}