5

I run ps -ejH | less. The output includes ps and less as well.

What is the reason? I thought it would work as follows:

  1. First, ps will run and it will list all processes existing at that moment.
  2. Then, the output of ps will be fed into less.

But according to this logic, neither ps not less should appear in the output of ps.

So, why are these processes included in the output of ps? Does ps work a bit differently that I have described?

Utku
  • 1,433

3 Answers3

12

The shell starts both, to establish the ends of the pipe, so ps sees itself as well as the process at the other end of the pipe.

Thomas Dickey
  • 76,765
1

"But according to this logic, neither ps not less should appear in the output of ps."

Yes, so your logic is wrong, because they both appear. When you run a command in a Un*x shell, very few (if any) actually run in the shell. A separate process is forked to run that command.

When you pipe two commands together, both commands are launched in separate processes and stdout of the first linked to stdin of the second.

So, very shortly after you execute ps|less, you have three processes: one running your shell, one running ps, and one running less. As the output is generated by ps, it will be worked on in parallel (timesliced as needed) by less. Both commands run in parallel, not sequentially, with minimal buffering.

As ps works its way through the process list, it finds and displays both itself and less, and the parent shell too, and the parent's parent, and so on up to init. And everything else on the system. That is why your output includes both ps and less.

-1

Use

ps -ef | grep [l]ess

to avoid less.

  • [l]ess match less as regexp but not as fixed string.
Archemar
  • 31,554