Ubuntu – Does ps output show a process even if it is not running

processps

Why does the ps shows a process even if it is not running. While Firefox is running:

$ echo $(ps aux | awk  '/firefox/{print $2}')
5964 6041

But when Firefox is not running, I tried to run the same command. It showed a different PID each time.

I tried grepping it:

$ ps aux | grep firefox
greenpa+  6056  0.0  0.0  15956   948 pts/11   S+   09:29   0:00 grep --color=auto firefox

What does it mean?

Best Answer

And this is why you shouldn't grep or otherwise parse the output of ps for matching commands, but use tools like pgrep and pidof.

When you run ps | grep foo, the grep foo process is also listed by ps - therefore grep foo matches itself along with any other foo processes. The exact same thing happens when you do echo $(ps aux | awk '/firefox/...) - the awk command matches itself.

Indeed, depending on what output you want from ps, you might be better off using pgrep's output with ps. For example, the states of all Google Chrome processes in my system:

ps -p $(pgrep -d, chrome) -o pid,state

pgrep's flexibility in this regard is very useful - note how I can specify an output delimiter with -d, then use it as PID list argument to ps. pgrep and pkill are also capable of reading from a PID file.

Related Question