Find the process ID (PID) of a given program, using ps or pidof

Written by
Date: 2012-06-08 17:10:43 00:00


There are times when you need to know the PID (process ID) of a given program, this is usefull specially when you want to kill a program, or daemon.

We'll use ps, pidof and pgrep to accompish this task.

ps

ps is the one I use the most, here is how:

ps auxw | grep nginx

The output could be something like this:

root     13440  0.0  0.4   8652  1020 pts/1    S+   21:13   0:00 grep nginx
root     24002  0.0  0.2  34888   572 ?        Ss   Jun02   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/conf/nginx.conf
http     24003  0.0  0.7  35836  1904 ?        S    Jun02   1:06 nginx: worker process                        
http     24004  0.0  0.7  35728  1964 ?        S    Jun02   1:06 nginx: worker process                        
http     24005  0.0  0.8  35688  2032 ?        S    Jun02   1:04 nginx: worker process                        
http     24006  0.0  0.7  35816  1856 ?        S    Jun02   1:05 nginx: worker process

Where the second column is the PID or PIDs of the different processes.

pidof

pidof nginx

Here the output is only the PID numbers.

24006 24005 24004 24003 24002

pgrep

pgrep nginx

The output once again, is only the PID numbers.

24002
24003
24004
24005
24006

If you want to count the number of processes running:

pidof nginx | wc -w

And if you want to do the same with pgrep

pgrep nginx | wc -l