I am confused by how linux could let application read from pipe like “cat /etc/hosts | grep ‘localhost'”. I know in a independent program fork a child and communicate by pipe between each other. But for two independent program communicating by pipe I don’t know how.
In example “cat /etc/hosts | grep ‘localhost'” How could Grep know which file descriptor it should read to get the input from “cat /etc/hosts”. Is there a “conventional” pipe provided by OS, to let Grep know where to get the input? I want to know the mechanism behind this.
I am confused by how linux could let application read from pipe like cat
Share
grep in your example gets it from stdin. It is the shell’s responsibility to call
pipe(2)to create the pipe and thendup2(2)in each of thefork(2)children to assign their end of the pipe to stdin or stdout before calling one of theexec(3)functions to actually run the other executables.