How to kill a process giving it a number of seconds before a doing the forced kill

killprocess

I do have the PID of the process to be killed but I do want to give it the chance to die peacefully, without doing a -9.

Expected behaviour: check if PID is still running for up to ten seconds and do a kill -9 on it.

Extra bonus if you could do this in a single line.

Best Answer

A better way to do this (that prevent killing the same PID for a different process) is:

 function kill_gracefully() {  
    pid=$1; [[ -z $pid ]] && return;  # check arg
    kill $pid; # kill once

    i=0;    
    while kill -0 $pid; do  # while pid is alive
       sleep 0.1;      
       ((i+=1));  # count ++
       if [[ $i -gt 10 ]];then    # wait for 10 secs at most
           kill -9 $pid;          # kill if timeout
           break;  
       fi;
    done;     
}

The above method may fail on a heavy loaded system (that forks frequently)