51 lines
1.2 KiB
C
51 lines
1.2 KiB
C
#include "kernel/types.h"
|
|
#include "user/user.h"
|
|
|
|
void pipeline(int leftfd) {
|
|
int pipefd[2];
|
|
int p; read(leftfd, &p, sizeof(p));
|
|
printf("prime %d\n", p);
|
|
int n;
|
|
int has_right = 0;
|
|
while (read(leftfd, &n, sizeof(n)) > 0) {
|
|
if (n % p != 0) {
|
|
if (!has_right) {
|
|
has_right = 1;
|
|
pipe(pipefd);
|
|
if (fork() == 0) {
|
|
close(pipefd[1]);
|
|
pipeline(pipefd[0]);
|
|
} else {
|
|
close(pipefd[0]);
|
|
}
|
|
}
|
|
write(pipefd[1], &n, sizeof(n));
|
|
}
|
|
}
|
|
close(leftfd);
|
|
if (has_right) {
|
|
close(pipefd[1]);
|
|
while(wait(0) != -1);
|
|
}
|
|
exit(0);
|
|
}
|
|
|
|
int main(int argc, char** argv) {
|
|
int pipefd[2];
|
|
pipe(pipefd);
|
|
int pid = fork();
|
|
if (pid != 0) {
|
|
close(pipefd[0]); // no need to read in the feeding proc
|
|
for (int i = 2; i <= 35; ++ i) {
|
|
write(pipefd[1], &i, sizeof(i));
|
|
}
|
|
close(pipefd[1]);
|
|
while(wait(0) != -1);
|
|
exit(0);
|
|
}
|
|
else {
|
|
close(pipefd[1]); // pipeline proc will have its own write pipe
|
|
pipeline(pipefd[0]);
|
|
}
|
|
exit(0);
|
|
} |