Pipes, Redirection, and File Descriptors

In this lab, you will get deeper understanding of the dup and pipe stystem calls. Read and understand codes. Run them to see their behavior.

open in GitHub Codespaces.

To build everything:

make

1-dup.c

  • Opens cats.txt and redirects stdout to that file using dup2.
  • Writes "cat 1" with write(), then "cat 2" with printf().

Question: What ends up inside cats.txt after running this program?

2-dup2.c

  • Opens cats.txt in append mode (so you don’t overwrite the existing content).
  • Redirects stdout to the file.
  • Prints "cat 3".

Question: After this, what does cats.txt contain?

3-copy.c

  • Opens cats.txt for reading and dogs.txt for writing.
  • Copies content byte by byte using read() and write().

Question: Why do we need two loops to write? When does bytesRead not return 1024 (the size of the buffer)?

4-pipe-one-process.c

  • Creates a pipe inside a single process.
  • Writes "meow" into the pipe, then reads it back.

Question: What happens if you try to read() again after the pipe is empty?

5-redirect.c

  • Redirects stdin from scores.csv and stdout to out.txt.
  • Executes:
grep niko < scores.csv > out.txt

Question: grep reads from stdin and writes to stdout. How do we change grep’s behavior to read from scores.csv and write to out.txt without changing grep’s code?

6-pipe-ls-wc.c

  • Implements:

    ls -l | wc -l
  • Two children: one runs ls, the other runs wc.

Question: Does it matter if ls runs before wc or wc runs before ls?

7-pipe-parent-child.c

  • Parent writes "meow" into the pipe.
  • Child reads and prints "From parent: meow".

Question: What happens if the parent does not close the write end after writing?

8-pipe-chain.c

  • Implements:

    cat scores.csv | grep niko | cut -f2 -d','
  • Three processes chained by two pipes.

Questions

  1. Which process reads from p1, which writes to p2?
  2. What is the final output if scores.csv contains a line with "niko,95"?
Back to top