7

In a pipeline such as command1 | command2,

  • are the commands run simultaneously (i.e. have the same lifetime), or
  • command2 starts to run at the time command1 exits, or
  • something else?

My question arises when I heard that the commands' processes form a process group. If they don't have the same lifetime, isn't the process group of the commands' processes meaningless?

Tim
  • 101,790

2 Answers2

9

The processes are started at the same time, and will run concurrently, but they don't have to stop at the same time. The shell will consider the entire pipeline to have terminated (and display a new prompt) when both processes have terminated.

If command2 ends before command1 does (or closes its standard input stream), and command1 then attempts to write output, there's nowhere for that output to go. Then command1 will receive a SIGPIPE signal, whose default action is to abort command1. But command1 itself can override this default such that it gets to continue running instead. In that case its attempts to write output will produce an ordinary I/O error (EPIPE) which it can react to however it wants.

1

"|"` AKA, "Pipes"....pipes let you use the output of a program as the input of another one" . So if let's say we do this:

user$ cat SHAHashing.java | grep main
    public static void main(String[] args)throws Exception

as you can see the cat executed first displaying the page's contents "THE OUTPUT" , and then grep for the string main .

Now lets assume I mistyped CAT like this:

user$ cats SHAHashing.java | grep main
-bash: cats: command not found

No output "wrong command" , grep will execute but with nothing to do .hence .... cats causeed the first command to terminate with status "exit 1".

z atef
  • 1,068
  • 1
    grep does execute in the second example too. It just doesn't have much to do, because its input ends immediately. You can observe this by doing, e.g. cats and dogs | echo hello, which will output hello, while complaining that there are no cats. The error message about the missing cats is being written to the first command's standard error stream, which is not redirected by default. But try cats and dogs 2>&1 | tr a u – hmakholm left over Monica Apr 06 '15 at 01:42