primes finished

This commit is contained in:
2025-02-27 11:11:09 +08:00
parent b5dcfc539f
commit 220553c3b8
4 changed files with 63 additions and 0 deletions

1
.gitignore vendored
View File

@ -19,6 +19,7 @@ user/usys.S
xv6.out* xv6.out*
.vagrant/ .vagrant/
submissions/ submissions/
mkfs/mkfs
ph ph
barrier barrier
/lab-*.json /lab-*.json

View File

@ -190,6 +190,7 @@ UPROGS=\
$U/_zombie\ $U/_zombie\
$U/_sleep\ $U/_sleep\
$U/_pingpong\ $U/_pingpong\
$U/_primes\

BIN
mkfs/mkfs Normal file → Executable file

Binary file not shown.

61
user/primes.c Normal file
View 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);
}