Section 7: Pipes

The code for this section can be found here.

Discussion: Pipes and Files, Oh My!

Discussion A. What are pipes? What concept do pipes allow us to implement?

Discussion B. Pipes are implemented using a familar abstraction, file descriptors. In terms of their functionality, in what ways are pipes similar to files? In what ways are they different?

Question 1: Piping PIDs

Mario the plumber recently switched careers to programming and is learning about pipes. He's designing a program where a parent process spawns a child process that writes data to its parent process (which, in turn, reads the data) through a pipe. However, Mario needs help understanding why his program works and how the pipe buffer in the OS changes as his program executes.

The pseudocode for Mario's program is below:

create a single pipe for parent-child communication
create a child process

child process code:
    close the read end of the pipe
    create five grandchild processes
    write the five grandchild process IDs into the pipe
    close the write end of the pipe

parent process code:
    close the write end of the pipe
    while data can be read from the pipe:
        read the next PID from the pipe and print it
    wait for the child process to terminate
    close the read end of the pipe

QUESTION 1A. What operations in Mario's code involve reading or writing data to the pipe? What order(s) could these operations occur in, and why?

QUESTION 1B. A computer's operating system implements pipes using a kernel-based buffer of finite size. Since Mario runs his program on an old computer, the pipe implementation he works with only provides 12 bytes of kernel space per pipe. Using an order of reading and writing operations from QUESTION 1A, update the diagram below as Mario's program reads from and writes to the pipe buffer.


Hint: The size of a pid_t (the type used for PIDs) is 4 bytes. What should happen if a process tries to write to the pipe but the buffer is full?

Question 2: Pipe Networks

Luigi, following in his brother's footsteps, has also decided he wants to become a C programmer. Like his brother, Luigi is trying to design a program where three processes can communicate (both read and write) via pipes. He wants each pipe to be unidirectional (only one process can read from and only one process can write to each pipe) and have each process be able to communicate with all other processes.

QUESTION 2A. Describe an arrangement of pipes Luigi could use to implement his idea. Make sure to describe which processes close which file descriptors. Processes should not have access to any extraneous file descriptors. Using pseudocode is fine!

QUESTION 2B. Luigi wants to incorporate even more processes into his program. How does the arrangement of Luigi's pipes change if he wants to use 4 child processes? What about an arbitrary number of child processes?