Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

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)

share|improve this answer
kill -- "$pid"; sleep 10; kill -s KILL -- "$pid"

If on a debian based system:

echo "$pid" | start-stop-daemon --pidfile /dev/stdin --stop --oknodo --name "$process_name" --user "$user" --retry 10

Which allows you to specify matching criteria (like user name and command name) to avoid killing the wrong process in case the pid has been reused.

share|improve this answer
2  
I would add extra checks after the sleep, possibly with ps to make sure that the process is still up, and the pid is still assigned to the same process. –  rahmu Oct 31 '12 at 13:58
    
@rhamu, No need to check if it's up. Doing a kill on an existing pid is harmless, kill will just fail. Checking it's the same process will be based on heuristics. It will be possible to a certain level of certainty in most cases, but not guaranteed in most cases. –  Stéphane Chazelas Oct 31 '12 at 14:08
    
@StephaneChazelas You can at least check that it hasn't been reassigned to an unrelated process by checking the command line and parent. It can produce false positives and false negatives, but it's less risky overall. –  Gilles Oct 31 '12 at 22:36
    
@Gilles. Yes, as I said, it will depend on the case. For instance, the command line of one process may genuinely change through a call to execve(2) and the ppid as well if the parent dies. See my start-stop-daemon answer for checking the user and command name. –  Stéphane Chazelas Nov 1 '12 at 7:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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