bash:在 while 循环中进行计数器(kill 和 kill -9)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15067229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash: counter inside a while loop (kill and kill -9)
提问by knocte
So I've learnt recently that kill is not a synchronouscommand, so I'm using this while loop in bash, which is awesome:
所以我最近了解到kill 不是一个同步命令,所以我在 bash 中使用了这个 while 循环,这很棒:
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".
但是,在某些情况下(非常罕见,但仍然会发生)进程会卡住,并且不会对终止信号起作用。在这些情况下,杀死应用程序的唯一方法是使用“ 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?
所以我想知道,如何修改上面的 while 循环,在 bash 中,仅当循环达到第 10 次迭代时才使用 -9 参数?
回答by Davide Berra
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
回答by kojiro
Sure, use a counter, but that's a little ham-fisted.
当然,使用计数器,但这有点笨手笨脚。
What you probably really want to do is use 0as your signal, which will do nothing to the process, but let you check if the process is still alive. (kill -0 $pidwill return a nonzero exit status if the process doesn't exist.) And then, you know, don't just kill -9it. 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.
您可能真正想要做的是0用作您的信号,它不会对进程产生任何影响,但让您检查进程是否还活着。(kill -0 $pid如果进程不存在,将返回一个非零退出状态。)然后,你知道,不要只是kill -9它。进程不会无缘无故地卡住,它们卡住是因为它们无法释放资源,例如发生网络或文件系统阻塞时。解决块,然后进程可以自行清理。
回答by Karoly Horvath
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
回答by cdarke
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

