kill, pkill & killall

The kill command is the venerable process assassin. In the most basic invocation without any flags and just the PID we want to terminate...

# the following 5 invocations of kill are exactly the same
root:~> kill 26547
root:~> kill ­-TERM 26547
root:~> kill ­-s TERM 26547
root:~> kill ­-15 26547
root:~> kill ­-s 15 26547

kill will send a TERM signal to the process. If the process has not been set to handle the signal, the process will be terminated. There are times though in which processes are set to ignore TERM signals and the only way to kill them would be using the SIGKILL signal. With the "-l" flag we get a reminder of all signals:

We can kill more than one process in one shot:

root:~> kill -­9 1356 6554 7667

It is important to remember that we only can kill processes owned by our user unless we are root or use sudo. And we can send signals to threads in a process but any thread within that process might handle it. In other words, a kill signal will kill the whole process rather than a particular thread.

If we know the command a certain PID is running but don't know the PID itself, we can use either of these 2 options:

root:~> kill -­9 `pgrep script.sh`
root:~> pkill -­9 script.sh

Apart from sending signals, the options for pkill are the same as those for pgrep which we shall cover a bit later.

If we need to kill a number of processes it might be better to use killall as it has more advanced matching criteria.

The "-I" flag makes the search case insensitive:

root:~> killall -­I Gedit

The "-i" flag prompts for kill confirmation (advisable!):

root:~> killall -­I Gedit ­-i
Kill gedit(18035) ? (y/N) n

The "-u" flag only matches processes owned by a specific user:

root:~> killall ­-9 -­I Gedit ­-i -­u marc

The "-g" flag matches all processes within the process group for the kill:

root:~> killall ­-15 ­-I Gedit -­i -­g

The "-o" flag matches processes older than <integer> s, m, h, d, w, M or Y:

root:~> killall ­-SIGHUP ­-u marc -­o 1m ­-i gedit

The "-y" flag matches processes younger than <integer> s, m, h, d, w, M or Y:

root:~> killall ­-9 -­u marc ­-y 5m ­-i gedit

The "-Z" flag matches processes whose SELinux context matches the regex:

root:~> killall -­SIGKILL ­-Z "NetworkManager_t" -­i NetworkManager

The remaining flags are:

• the ­q flag suppresses the error message if no processes were killed

• the ­e flag matches exactly the whole given string rather than just the first 15 characters to avoid incomplete matches getting killed!

• the ­w flag waits for all killed processes to actually die before returning control

• the ­v flag is the usual verbosity option

As a last note, if we specify a filename starting with “/” (fullpath) as the matching string, then all the processes executing that file will be matched and killed.

 

 

<< pstree                  nice, renice & ionice >>