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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With