Skip to content

Commit

Permalink
Lab util: primes
Browse files Browse the repository at this point in the history
  • Loading branch information
foyoodo committed Mar 7, 2021
1 parent f5693b0 commit 1d04c10
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ UPROGS=\
$U/_ls\
$U/_mkdir\
$U/_pingpong\
$U/_primes\
$U/_rm\
$U/_sh\
$U/_sleep\
Expand Down
53 changes: 53 additions & 0 deletions user/primes.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include "kernel/types.h"
#include "user/user.h"

void
filter(int *pin)
{
int n, buf, pout[2];
pipe(pout);
close(pin[1]);
if (read(pin[0], &n, sizeof(int))) {
printf("prime %d\n", n);
if (fork() == 0) {
filter(pout);
exit(0);
} else {
close(pout[0]);
while (read(pin[0], &buf, sizeof(int))) {
if (buf % n != 0) {
write(pout[1], &buf, sizeof(int));
}
}
close(pout[1]);
wait(0);
}
}
exit(0);
}

int
main(int argc, char *argv[])
{
if (argc > 1) {
fprintf(2, "Usage: primes\n");
exit(1);
}

int p[2];
pipe(p);

if (fork() == 0) {
filter(p);
exit(0);
} else {
close(p[0]);
for (int i = 2; i <= 35; ++i) {
write(p[1], &i, sizeof(int));
}
close(p[1]);
wait(0);
}

exit(0);
}

0 comments on commit 1d04c10

Please sign in to comment.