I am familiar with kill
command , and most of the time we just use kill -9
to kill a process forcefully, there are many other signals that can be used with kill
. But I wonder what are the use cases of pkill
and killall
, if there is already a kill command.
Do pkill
and killall
use the kill
command in their implementation? I mean they are just wrappers over kill
or they have their own implementation?
I would also like to know how pgrep
command gets the process id from the process name.
Do all these commands use the same underlying system calls? Is there any difference from a performance point of view, which one is faster?
Best Answer
The
kill
command is a very simple wrapper to thekill
system call, which knows only about process IDs (PIDs).pkill
andkillall
are also wrappers to thekill
system call, (actually, to the libc library which directly invokes the system call), but can determine the PIDs for you, based on things like, process name, owner of the process, session id, etc.How
pkill
andkillall
work can be seen usingltrace
orstrace
on them. On Linux, they both read through the/proc
filesystem, and for each pid (directory) found, traverses the path in a way to identify a process by its name or other attributes. How this is done is technically speaking, kernel and system specific. In general, they read from/proc/<PID>/stat
which contains the command name as the 2nd field. Forpkill -f
andpgrep
examine the/cmdline
entry for each PID's proc entry.pkill
andpgrep
use thereadproc
system call, whereaskillall
does not. I couldn't say if there's a performance difference: you'll have to benchmark that on your own.