3

If I want to check if something is running, I do ps aux | grep flamethrower, expecting just to show the processes containing flamethrower in the name. This will always find at least one process, as grep flamethrower matches this criteria.

Is there some way to check for a specific process, in a cleaner way?

1 Answers1

3

The usual way would be to use pgrep:

$ pgrep init
1
2215
6300
$ ps ax | grep init
    1 ?        Ss     6:41 /sbin/init
 2215 ?        Ss     1:54 init --user --restart --state-fd 26
 6300 ?        S      0:00 init --user --startup-event indicator-services-start
17522 pts/10   S+     0:00 grep --color=auto init

Note that you might need to use other tricks with pgrep as well, if you use it with watch and -f:

$ watch pgrep init -fa
Every 2.0s: pgrep init -fa                                                                                                                                                                                               
Wed Dec  3 19:19:47 2014

1 /sbin/init
2215 init --user --restart --state-fd 26
6300 init --user --startup-event indicator-services-start
18233 watch pgrep init -fa
18234 watch pgrep init -fa
18235 sh -c pgrep init -fa
$ watch pgrep [i]nit -fa
Every 2.0s: pgrep [i]nit -fa                                                                                                                                                                                           Wed Dec  3 19:20:42 2014

1 /sbin/init
2215 init --user --restart --state-fd 26
6300 init --user --startup-event indicator-services-start
muru
  • 72,889
  • 1
    BTW, congrats on getting to 2k! – slm Dec 03 '14 at 13:36
  • I would use ps ax | grep [i]nit (this work for a fixed string of course) – Archemar Dec 03 '14 at 13:43
  • @Archemar I need to do that with pgrep too, if use it with watch. – muru Dec 03 '14 at 13:47
  • @slm thanks. Looking forward to more involvement here. – muru Dec 03 '14 at 13:48
  • But: from pgrep manual: «The process name used for matching is limited to the 15 characters present in the output of /proc/pid/stat. Use the -f option to match against the complete command line, /proc/pid/cmdline.», So, what if I wan't to search on process complete (not-truncated) names (without full path or arguments)? – Pablo A Mar 06 '18 at 01:36
  • @PabloBianchi what's the name here? Name of the executable, or argv[0]? – muru Mar 06 '18 at 02:20
  • @muru Name of executable but not /proc/PID/comm (truncated as Name on status), the last part of cmdline. A guy called Luben Tuikov also thing would be nice more bytes. – Pablo A Mar 06 '18 at 02:41
  • @PabloBianchi you'd have to script that, since comm, stat have truncated names, cmdline would have argv[0] (so may not be the executable name). In bash, for example: for proc in $(ps -eo pid=); do f=$(readlink /proc/$proc/exe); [[ ${f##*/} =~ pattern ]] && echo $proc; done – muru Mar 06 '18 at 03:21