knocte
knocte

Reputation: 17969

bash: counter inside a while loop (kill and kill -9)

So I've learnt recently that kill is not a synchronous command, so I'm using this while loop in bash, which is awesome:

while kill PID_OF_THE_PROCESS 2>/dev/null; do sleep 1; done

However, there are cases (very rare, but they still happen) in which the process gets stuck, and it doesn't act on the kill signal. In these cases, the only way to kill the app is using "kill -9".

So I'm wondering, how would one modify the while loop above, in bash, to use the -9 argument only if the loop has reached the 10th iteration?

Upvotes: 6

Views: 6678

Answers (4)

cdarke
cdarke

Reputation: 44394

There are several ways to achieve this, but you did ask to modify your existing loop, so:

count=0
while kill PID_OF_THE_PROCESS 2>/dev/null
do 
    sleep 1; 
    (( count++ ))
    if (( count > 9 ))
    then
        kill -9 PID_OF_THE_PROCESS 2>/dev/null
     fi
done

Upvotes: 0

Davide Berra
Davide Berra

Reputation: 6568

As other users said.... you have to fix the cause of the block before use this brutal method... anyway... try this

#!/bin/bash

i=0

PID_OF_THE_PROCESS="your pid you can set as you like"

# send it just once
kill $PID_OF_THE_PROCESS 2>/dev/null;

while [ $i -lt 10 ];
do
    # still alive?
    [ -d /proc/$PID_OF_THE_PROCESS ] || exit;
    sleep 1;
    i=$((i+1))
done

# 10 iteration loop and still alive? be brutal
kill -9 $PID_OF_THE_PROCESS

Upvotes: 3

Karoly Horvath
Karoly Horvath

Reputation: 96266

It's enough to send the signal once.

kill $PID 2>/dev/null
sleep 10;
if kill -0 $PID 2>/dev/null
  kill -9 $PID
fi

For your counter question:

c=0
while true; do
    echo $c;
    c=$((c+1));
    if [ $c -eq 10 ]; then break; fi;
done

Upvotes: 1

kojiro
kojiro

Reputation: 77137

Sure, use a counter, but that's a little ham-fisted.

What you probably really want to do is use 0 as your signal, which will do nothing to the process, but let you check if the process is still alive. (kill -0 $pid will return a nonzero exit status if the process doesn't exist.) And then, you know, don't just kill -9 it. Processes don't get stuck for no reason, they get stuck because they can't let go of a resource, such as when network or filesystem blocking occurs. Resolve the block, then the process can clean up after itself.

Upvotes: 1

Related Questions