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 child returns. But how does shell internally handle the execution of piped commands ?
Share
Considering for example
cat | grep, the shell first forks itself to startcat, and then forks itself once more to startgrep.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. Thepipe(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 thedup2(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 usingdup2(2).This way both programs are unaware of a pipe because they just work with the standard input/output.