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 ofps
for matching commands, but use tools likepgrep
andpidof
.When you run
ps | grep foo
, thegrep foo
process is also listed byps
- thereforegrep foo
matches itself along with any otherfoo
processes. The exact same thing happens when you doecho $(ps aux | awk '/firefox/...)
- theawk
command matches itself.Indeed, depending on what output you want from
ps
, you might be better off usingpgrep
's output withps
. For example, the states of all Google Chrome processes in my system: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 tops
.pgrep
andpkill
are also capable of reading from a PID file.