Hack 93. Kill Command Examples

by Ramesh

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

  1. 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.

  1. # ps aux | grep httpd
  2. USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
  3. apache 31186 0.0 1.6 23736 17556 ? S Jul26 0:40 /usr/local/apache2/bin/httpd
  4. apache 31187 0.0 1.3 20640 14444 ? S Jul26 0:37 /usr/local/apache2/bin/httpd
  5.  
  6. # 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.

  1. # kill -9 31186 31187

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

  1. function psgrep ()
  2. {
  3. ps aux | grep "$1" | grep -v 'grep'
  4. }
  5.  
  6. function psterm ()
  7. {
  8. [ ${#} -eq 0 ] && echo "usage: $FUNCNAME STRING" && return 0
  9. local pid
  10. pid=$(ps ax | grep "$1" | grep -v grep | awk '{ print $1 }')
  11. echo -e "terminating '$1' / process(es):\n$pid"
  12. kill -SIGTERM $pid
  13. }

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

  1. # psgrep http
  2.  
  3. USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
  4. apache 31186 0.0 1.6 23736 17556 ? S Jul26 0:40 /usr/local/apache2/bin/httpd
  5. apache 31187 0.0 1.3 20640 14444 ? S Jul26 0:37 /usr/local/apache2/bin/httpd
  6.  
  7. # psterm httpd
  8.  
  9. terminating 'httpd' / process(es):
  10. 31186
  11. 31187