Primes

Your goal is to use pipe and fork to set up the pipeline. The first process feeds the numbers 2 through 280 into the pipeline. For each prime number, you will arrange to create one process that reads from its left neighbor over a pipe and writes to its right neighbor over another pipe. Since xv6 has limited number of file descriptors and processes, the first process can stop at 280.

Some hints:

  • Be careful to close file descriptors that a process doesn't need, because otherwise your program will run xv6 out of resources before the first process reaches 280.

  • Once the first process reaches 280, it should wait until the entire pipeline terminates, including all children, grandchildren, &c. Thus the main primes process should only exit after all the output has been printed, and after all the other primes processes have exited.

  • Hint: read returns zero when the write-side of a pipe is closed.

  • It's simplest to directly write 32-bit (4-byte) ints to the pipes, rather than using formatted ASCII I/O.

  • You should create the processes in the pipeline only as they are needed.

  • Add the program to UPROGS in Makefile.

  • If you get an infinite recursion error from the compiler for the function primes, you may have to declare void primes(int) __attribute__((noreturn)); to indicate that primes doesn't return.

Your solution should implement a pipe-based sieve and produce the following output:

    $ make qemu
    ...
    init: starting sh
    $ primes
    prime 2
    prime 3
    prime 5
    prime 7
    prime 11
    prime 13
    prime 17
    prime 19
    prime 23
    prime 29
    prime 31
    ...
    $

Last updated