-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprimes.c
More file actions
70 lines (64 loc) · 1.33 KB
/
primes.c
File metadata and controls
70 lines (64 loc) · 1.33 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
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
void handle(int nums);
int main(int argc, char const *argv[]) {
int p1[2];
pipe(p1);
int pid = fork();
switch (pid) {
case -1:
exit(1);
case 0:
close(p1[1]); // 不需要写
handle(p1[0]);
close(p1[0]);
exit(0);
default:
close(p1[0]); // 不需要读
for (int i = 2; i <= 280; i++) {
write(p1[1], &i, sizeof(int));
}
close(p1[1]);
wait(0);
exit(0);
}
}
void handle(int nums) {
int prime;
int ok = read(nums, &prime, sizeof(int));
if (ok <= 0) {
close(nums);
return;
}
printf("prime %d\n", prime);
int p2[2];
pipe(p2);
int pid = fork();
switch (pid) {
case -1:
exit(1);
case 0:
close(nums);
close(p2[1]);
handle(p2[0]);
close(p2[0]);
exit(0);
default:
close(p2[0]); // 不需要读
while (1) {
int num;
int ok = read(nums, &num, sizeof(int));
if (ok <= 0) {
close(nums);
break;
}
if (num % prime != 0) {
write(p2[1], &num, sizeof(int));
}
}
close(p2[1]);
wait(0);
exit(0);
}
}