You asked about the order and I think that this is a very important aspect to the matter. This is not random (as Gilles tries to say in his answer).
Here is a
ps -ef piped to the
$ ps -ef | grep .
alexis 37188 55443 0 20:17 pts/4 00:00:00 ps -ef
alexis 37189 55443 0 20:17 pts/4 00:00:00 grep --color=auto .
Note: I removed all the other processes from the output since they are of no importance to the matter.
As we can see, there is a
ps -ef and a
grep --color=auto . in the output. Can you answer your question now?
ps command has PID 37,188 and the
grep command has PID 37,189. Clearly, they were created left to right and no shell should do this differently.
Technically, in C, we create pipes with the
pipe(2) function which gives us two file descriptors. One is going to be used as the
ps and the other as the
grep. It is easy enough to hold on the file descriptor for
stdin until after you started
Further, if you look at your system configuration like so:
$ getconf -a | grep PIPE_BUF
you notice those two parameters defining the minimum guaranteed size of the pipe in bytes. Since Linux 2.6, the default size is 64Kb. Also the absolute maximum number of bytes is defined in:
$ cat /proc/sys/fs/pipe-max-size
and we can see this is 1Mb. Once the pipe is full, the outputter (
ps in our first example) blocks until data gets read by the process on the other side of the pipe (
grep in our first example).
In other words, since the output of
ps is much less than the size of a pipe:
$ ps -ef | wc
1132 10819 121435
(i.e. about 120Kb of output on my computer at the moment...)
The pipeline won't get blocked at all.
For streamed data over 1Mb, it does get blocked at some point. If
grep was not started immediately, it would never start since the
write() call in the first command would then be blocked.
So the processes are very quickly started back to back, but for most of the time, they run in parallel (or concurrently if you have a single processor). That is, the
ps command will die first. This marks the pipe as "done" (you get the
EOF signal when reading data from it) and that's how the next tool knows it is done and it also dies once it processes the last few bytes it received.
Conversely, if a process on the right side of a pipe dies early (before the one of the left is done writing to the pipe), then the process on the left receives the
SIGPIPE signal as soon as it tries to write to the pipe. This is done like so to make sure that the pipeline dies quickly if any of the processes within it dies.