Hack 93. Kill Command Examples

kill command can be used to terminate a running process. Typically this command is used to kill processes that are hanging and not responding.

Syntax: kill [options] [pids|commands]

How to kill a hanging process?

First, identify the process id of the particular process that you would like to kill using the ps command. Once you know the process id, pass it as a parameter to the kill command. The example below shows how to kill the hanging apache httpd process. Please note that typically you should use “apachectl stop” to stop apache.

# ps aux | grep httpd
USER       PID %CPU %MEM    VSZ    RSS TTY  STAT START  TIME COMMAND
apache   31186       0.0        1.6  23736 17556 ?        S          Jul26       0:40  /usr/local/apache2/bin/httpd
apache   31187       0.0        1.3  20640 14444 ?        S          Jul26       0:37  /usr/local/apache2/bin/httpd

# kill 31186 31187

Please note that the above command tries to terminate the process graciously by sending a signal called SIGTERM. If the process does not get terminated, you can forcefully terminate the process by passing a signal called SIGKILL, using the option -9 as shown below. You should either be the owner of the process or a privileged user to kill a process.

# kill -9 31186 31187

Another way to kill multiple processes easily is by adding the following two functions to the .bash_profile.

function psgrep ()
{
 ps aux | grep "$1" | grep -v 'grep'
}

function psterm ()
{
 [ ${#} -eq 0 ] && echo "usage: $FUNCNAME STRING" && return 0
 local pid
 pid=$(ps ax | grep "$1" | grep -v grep | awk '{ print $1 }')
 echo -e "terminating '$1' / process(es):\n$pid"
 kill -SIGTERM $pid
}

Now do the following, to identify and kill all httpd processes.

# psgrep http

USER       PID %CPU %MEM    VSZ    RSS TTY  STAT START  TIME COMMAND
apache   31186       0.0        1.6  23736 17556 ?        S          Jul26       0:40  /usr/local/apache2/bin/httpd
apache   31187       0.0        1.3  20640 14444 ?        S          Jul26       0:37  /usr/local/apache2/bin/httpd

# psterm httpd

terminating 'httpd' / process(es):
31186
31187

Comments on this entry are closed.

  • Amrit Kaur March 9, 2013, 3:18 am

    Its really gudd 🙂

  • William Harrison August 23, 2013, 6:12 pm

    If you show he command not found after editing .bash_profile, run the following so psgrep runs immediately.

    source .bash_profile

  • artickl September 24, 2013, 7:08 pm

    Kindly outdated information here, which is not working in some cases.

    Instead of creating additional function locally in bash, better to use widely installed:
    pgrep – to find processes pids by name (no “-v ‘grep'” which is not good in cases if you try to find some program with “grep” in the name)
    killall – killing all instances of specified program (allowed different signals be sent to all specified processes, such as ‘#killall -9 bash’)