summaryrefslogtreecommitdiff
path: root/user/primes.c
diff options
context:
space:
mode:
authorMole Shang <[email protected]>2024-01-17 11:33:39 +0800
committerMole Shang <[email protected]>2024-01-18 14:25:09 +0800
commit33ca12a4653752d179e6296c7ca2f91a626d30f3 (patch)
tree819af498462a8a0f725c408c08aa0dae53f6f07b /user/primes.c
parente6ef31e4b30af1f30a4d1385971df602a8446cac (diff)
downloadxv6-labs-33ca12a4653752d179e6296c7ca2f91a626d30f3.tar.gz
xv6-labs-33ca12a4653752d179e6296c7ca2f91a626d30f3.tar.bz2
xv6-labs-33ca12a4653752d179e6296c7ca2f91a626d30f3.zip
lab util: finish
Diffstat (limited to 'user/primes.c')
-rw-r--r--user/primes.c74
1 files changed, 74 insertions, 0 deletions
diff --git a/user/primes.c b/user/primes.c
new file mode 100644
index 0000000..b359524
--- /dev/null
+++ b/user/primes.c
@@ -0,0 +1,74 @@
+#include "kernel/types.h"
+#include "user/user.h"
+
+#define MAX 36
+#define FIRST_PRIME 2
+
+int
+generate_natural(); // -> out_fd
+int
+prime_filter(int in_fd, int prime); // -> out_fd
+
+int
+main(int argc, char* argv[])
+{
+ int prime;
+
+ int in = generate_natural();
+ while (read(in, &prime, sizeof(int))) {
+ // printf("prime %d: in_fd: %d\n", prime, in); // debug
+ printf("prime %d\n", prime);
+ in = prime_filter(in, prime);
+ }
+
+ close(in);
+
+ exit(0);
+}
+
+int
+generate_natural()
+{
+ int out_pipe[2];
+
+ pipe(out_pipe);
+
+ if (!fork()) {
+ for (int i = FIRST_PRIME; i < MAX; i++) {
+ write(out_pipe[1], &i, sizeof(int));
+ }
+ close(out_pipe[1]);
+
+ exit(0);
+ }
+
+ close(out_pipe[1]);
+
+ return out_pipe[0];
+}
+
+int
+prime_filter(int in_fd, int prime)
+{
+ int num;
+ int out_pipe[2];
+
+ pipe(out_pipe);
+
+ if (!fork()) {
+ while (read(in_fd, &num, sizeof(int))) {
+ if (num % prime) {
+ write(out_pipe[1], &num, sizeof(int));
+ }
+ }
+ close(in_fd);
+ close(out_pipe[1]);
+
+ exit(0);
+ }
+
+ close(in_fd);
+ close(out_pipe[1]);
+
+ return out_pipe[0];
+}