62 lines
1.1 KiB
C
62 lines
1.1 KiB
C
#include "kernel/types.h"
|
|
#include "user/user.h"
|
|
|
|
void redirect(int n, int pd[]) {
|
|
close(n);
|
|
dup(pd[n]);
|
|
close(pd[0]);
|
|
close(pd[1]);
|
|
}
|
|
|
|
void primes() {
|
|
int previous, next;
|
|
int fd[2];
|
|
|
|
while (read(0, &previous, sizeof(int))) {
|
|
printf("prime %d\n", previous);
|
|
|
|
if (pipe(fd) < 0) {
|
|
fprintf(2, "pipe failed\n");
|
|
exit(1);
|
|
}
|
|
|
|
if (fork() == 0) {
|
|
redirect(1, fd);
|
|
while (read(0, &next, sizeof(int))) {
|
|
if (next % previous != 0) {
|
|
write(1, &next, sizeof(int));
|
|
}
|
|
}
|
|
exit(0);
|
|
} else {
|
|
close(fd[1]);
|
|
redirect(0, fd);
|
|
}
|
|
}
|
|
}
|
|
|
|
int main(int argc, char *argv[]) {
|
|
int fd[2];
|
|
|
|
if (pipe(fd) < 0) {
|
|
fprintf(2, "pipe failed\n");
|
|
exit(1);
|
|
}
|
|
|
|
if (fork() == 0) {
|
|
redirect(1, fd);
|
|
for (int i = 2; i < 36; i++) {
|
|
write(1, &i, sizeof(int));
|
|
}
|
|
exit(0);
|
|
} else {
|
|
close(fd[1]);
|
|
redirect(0, fd);
|
|
primes();
|
|
}
|
|
|
|
exit(0);
|
|
}
|
|
|
|
|