Implement ls | less in C
In section 2.2, we see how pipe works for communication between parent and child processes. A familiar example of this kind of communication can be seen in all operating system shells.
pipe_lsless.c
implements shell command "ls | less" in C.
Analysis:
The parent uses the pipe for ls
output. That means it needs to change its standard output file descriptor to the writing end of the pipe. It does this via dup2()
system call and then executes ls
. The child will use the pipe for less
input. It changes its standard input file descriptor to the reading end of pipe by dup2(pfd[0], 0)
. Then child executes less
and the result is sent to standard output. Thus, the output of ls
flows into the pipe, and the input of less
flows in from the pipe. This is how we connect the standard output of ls
to the standard input of less
.
Last updated
Was this helpful?