Is there a common way or existing utility to do the following?

  • kill a process
  • Give it a few seconds to shut down gracefully
  • kill -9 it if it hasn't stopped
  • 1
    This SuperUser answer is useful but pgrep is not guaranteed to be available everywhere. Also it is bash-specific
    – iruvar
    Jul 16 '14 at 18:21
  • Agree with 1_CR's comment and the linked answer. Pretty much the only way to do it is to poll and sleep. Problem is, it is impossible to look inside the program and know whether sending a SIGTERM, SIGINT, etc. is actually causing it to try and terminate. Nor can you ever set a timeout large enough to account for programs that may take 1 minute, 2 minutes, an hour, 10 quadrillion millennia, etc. to successfully/gracefully terminate in response to a graceful termination signal. SIGKILL is basically "I can't afford to wait any longer, so just die". Jul 16 '14 at 18:33
  • The only change I'd make to that script from SU: If you have a bit more patience than 1 second, you can increase the sleep value (in seconds) to give the process more time to gracefully exit. DBs are famous for taking several seconds to flush their cached stuff in RAM to disk... Jul 16 '14 at 18:40

Usually I try to keep things as simple as:

kill $pid; sleep 5; kill -9 $pid

Or you can search a process by its name if you like:

pkill $pattern; sleep 5; pkill -9 $pattern

This is handy when you are working in a terminal, but for scripting you may prefer a more sophisticated solution from another answer.

  • Cleverly simple - you don't bother checking whether it has stopped because kill -9 $pid will have no effect if it has. +1 :) Jul 22 '14 at 19:45
  • 1
    @Nathan Long Or it will kill an innocent process if that $pid got recycled in the meantime. :)
    – PSkocik
    Jul 22 '15 at 2:10
  • @PSkocik Ooooh, good point... Jul 22 '15 at 17:29

Put this in your ~/.bashrc file. Use it like this killany program_name. It will try to kill any program with a matching name.

killany ()
    PS=$(ps aux)
    PIDS=$(echo "$PS" | \   
    awk -v proc="$1" '{ reg=proc; if(match($11$12$13$14,reg)) print $2 }')
    if [ -n "$PIDS" ]; then
        echo "killing pids '$PIDS'"
        kill $PIDS 2> /dev/null
        sleep 3
        kill -1 $PIDS 2> /dev/null
        sleep 2
        kill -9 $PIDS 2> /dev/null
        echo "none to kill"

"Kill Me Softly"

I just ran across project with a couple of small shell scripts for this.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.