2

Say, for example, we have the following executed in the shell:

ls | grep "abc" | wc

I understand how a child process would fork from the shell and how its a child, like this,

Shell (pid=12)
       \
        \
         ls (pid=13)

but I'm not sure how the pipe and the trailing commands fit in. Are they also children of the shell, and not ls?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
  • 1
    Are you familiar with the `pstree` utility? – Oliver Charlesworth Mar 03 '13 at 21:22
  • For OP: get an idea from [**this code**](http://www.ladweb.net/src/ladsh4.c.html) how shell actually implements `|` operator. search this line in code: `if (!(newJob.progs[i].pid = fork()))` Then you came to know ls, grep, wc are child processes of shell...The code is not bash code but Bash do similarly.. – Grijesh Chauhan Mar 03 '13 at 21:41

1 Answers1

2

Each component of the pipeline will be a child process of the shell. If you use pstree -p from another terminal, you'll probably see something like this:

...
sshd(11)---bash(12)-+-ls(13)
                    |-grep(14)
                    \-wc(15)
...

(assuming you can run this whilst your pipeline is still running!)

However, note that all the components will form a single process group.

The piping itself is a feature of Linux (or whatever OS you're using), it's not a separate user process. The shell creates some anonymous pipes, and hooks them up to the relevant file descriptors for each pair of processes in the pipeline.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680