Quote:
Originally Posted by
siba.s.nayak
Here A must finish before B starts. Because The output of A is the input for B.
That is not correct. It is undefined whether A or B starts first. They might start at the exactly the same time if there are multiple cpu's. A pipe can hold an undefined but finite amount of data.
If B tries to read from the pipe, but no data is available, B will wait until the data arrives. If B was reading from a disk, B might have the same problem and need to wait until a disk read finishes. A closer analogy would be reading from a keyboard. There, B would need to wait for a user to type. But in all of these cases, B has started a "read" operation and must wait until it finishes.
If A tries to write to the pipe, and the pipe is full, A must wait for some room in the pipe to become free. A could have the same problem if A was writing to a terminal. A terminal has flow control and can moderate the pace of data. In any event, to A, it has started a "write" operation and will wait until the write operation finishes.
A and B are behaving as co-processes, although not all co-processes will be communicating with a pipe. Neither is in full control of the other.
In a case, like:
A | sort
The sort command cannot output anything until it reads all of the data. So the sort command will do that, just as it would if it was reading from a file. Many other programs strive to read and write data if they can. This allows them to be used in long pipelines with data continuously flowing though the entire pipeline.