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:
make
1-dup.c
- Opens
cats.txt
and redirectsstdout
to 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.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 anddogs.txt
for 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
stdin
fromscores.csv
andstdout
toout.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 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.csv
contains a line with"niko,95"
?