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.
To build everything:
make1-dup.c
- Opens
cats.txtand redirectsstdoutto that file usingdup2. - Writes
"cat 1"withwrite(), then"cat 2"withprintf().
Question: What ends up inside cats.txt after running this program?
2-dup2.c
- Opens
cats.txtin append mode (so you don’t overwrite the existing content). - Redirects
stdoutto the file. - Prints
"cat 3".
Question: After this, what does cats.txt contain?
3-copy.c
- Opens
cats.txtfor reading anddogs.txtfor writing. - Copies content byte by byte using
read()andwrite().
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
stdinfromscores.csvandstdouttoout.txt. - Executes:
grep niko < scores.csv > out.txtQuestion: 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 -lTwo children: one runs
ls, the other runswc.
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
- Which process reads from
p1, which writes top2? - What is the final output if
scores.csvcontains a line with"niko,95"?