What is the difference between pidof and pgrep?

The programs pgrep and pidof are not quite the same thing, but they are very similar. For example:

$ pidof 'firefox'
5696
$ pgrep '[i]ref'
5696
$ pidof '[i]ref'
$ printf '%s\n' "$?"
1

As you can see, pidof failed to find a match for [i]ref. This is because pidof program returns a list of all process IDs associated with a program called program. On the other hand, pgrep re returns a list of all process IDs associated with a program whose name matches the regular expression re.

In their most basic forms, the equivalence is actually:

$ pidof 'program'
$ pgrep '^program$'

As yet another concrete example, consider:

$ ps ax | grep '[w]atch'
   12 ?        S      0:04 [watchdog/0]
   15 ?        S      0:04 [watchdog/1]
   33 ?        S<     0:00 [watchdogd]
18451 pts/5    S+     0:02 watch -n600 tail log-file
$ pgrep watch
12
15
33
18451
$ pidof watch
18451

Fox has mentioned that pgrep searches using regular expressions, while pidof does not.

But pgrep also has a lot more options available:

  • With -u "$UID" you can match only processes belonging to the current user.
  • With --parent you can find the child processes of a given process.
  • You can select the --oldest or --newest of the matching processes.
  • ...and various others listed on the man page...

Let's find out which package each process belongs to (on apt systems):

$ dpkg -S "$(which pidof)"
sysvinit-utils: /bin/pidof

$ dpkg -S "$(which pgrep)"
procps: /usr/bin/pgrep

Tags:

Process