primes finished
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@ -19,6 +19,7 @@ user/usys.S
|
||||
xv6.out*
|
||||
.vagrant/
|
||||
submissions/
|
||||
mkfs/mkfs
|
||||
ph
|
||||
barrier
|
||||
/lab-*.json
|
||||
|
||||
61
user/primes.c
Normal file
61
user/primes.c
Normal file
@ -0,0 +1,61 @@
|
||||
#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);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user