I want to understand that how does shell executes piped commands ? e.g. cat | more. I am aware that for executing a normal command shell does a fork, execute it and then ch
Considering for example cat | grep
, the shell first forks itself to start cat
, and then forks itself once more to start grep
.
Before calling one of the exec*
family of functions in the two newly created processes to start the two programs, the tricky part is setting up the pipe and redirecting the descriptors. The pipe(2)
system call is used in the shell process before forking to return a pair of descriptors which both children inherit - a reading end and a writing end.
The reading end will be closed in the first process (cat
), and stdout will be redirected to the writing end using the dup2(2)
system call. Similarly, the writing end in the second process (grep
) will be closed and stdin will be redirected to the reading end again using dup2(2)
.
This way both programs are unaware of a pipe because they just work with the standard input/output.
It sets up a pipe using the pipe system call, forks two processes instead of one and attaches one end of the pipe to the first process' stdout and the other end to the second process' stdin.
The same, just the stdout of one application is the same as the next stdin. http://unixwiz.net/techtips/remap-pipe-fds.html