// The prime of current process. // Initialized with `max_n + 1` for `max_n % current != 0`. int current = max_n + 1;
// The fd to read data from the left process. int r_fd = -1;
// The fd to write data to the left process. int w_fd = -1;
voidhandle(int x);
voidlog_prime(int x){ printf("prime %d\n", x); }
voidhandle_until_close(){ int x; while (read(r_fd, &x, sizeof(x)) != 0) { handle(x); }
if (w_fd != -1) { close(w_fd); }
close(r_fd); wait(0); exit(0); }
voidinit_r_proc(int cur_prime){ // Prepare a new pipe. int pipe_fds[2]; if (pipe(pipe_fds) < 0) { fprintf(2, "Failed to create pipe\n"); exit(-1); }
// Fork out a child process. int pid = fork(); if (pid < 0) { fprintf(2, "Failed to fork!\n"); close(pipe_fds[P_READ]); close(pipe_fds[P_WRITE]); return; }
current = cur_prime; log_prime(current); handle_until_close(); return; } }
voidhandle(int x){ if (x % current == 0) { return; }
// When x does not have a factor between [2, sqrt(x)], // it can be determined to be a prime. // Adding this optimization here to avoid too many processes are forked out. if (current <= max_n && current * current > max_n) { log_prime(x); return; }
intmain(int argc, char* argv[]){ if (argc < 2) { fprintf(2, "usage: xargs <command and args>.\n"); exit(-1); }
for (int i = 1; i < argc; ++i) { g_argv[g_argc++] = argv[i]; }
char* line; while (getline(&line) != -1) { execute(line); }
exit(0); }
实验结果
搞定!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
➜ xv6-labs-2024 git:(dev/util) ✗ ./grade-lab-util make: `kernel/kernel' is up to date. == Test sleep, no arguments == sleep, no arguments: OK (0.6s) == Test sleep, returns == sleep, returns: OK (0.9s) == Test sleep, makes syscall == sleep, makes syscall: OK (1.0s) == Test pingpong == pingpong: OK (1.0s) == Test primes == primes: OK (1.2s) == Test find, in current directory == find, in current directory: OK (1.0s) == Test find, in sub-directory == find, in sub-directory: OK (0.9s) == Test find, recursive == find, recursive: OK (1.2s) == Test xargs == xargs: OK (1.0s) == Test xargs, multi-line echo == xargs, multi-line echo: OK (0.7s) == Test time == time: OK Score: 110/110