Automating Killall then Killall level 9

旧城冷巷雨未停 提交于 2019-12-04 04:42:56

问题


Sometimes I want to killall of a certain process, but running killall doesn't work. So when I try to start the process again, it fails because the previous session is still running. Then I have to tediously run killall -9 on it. So to simplify my life, I created a realkill script and it goes like this:

PIDS=$(ps aux | grep -i "$@" | awk '{ print $2 }') # Get matching pid's.
kill $PIDS 2> /dev/null # Try to kill all pid's.
sleep 3
kill -9 $PIDS 2> /dev/null # Force quit any remaining pid's.

So, Is this the best way to be doing this? In what ways can I improve this script?


回答1:


Avoid killall if you can since there is not a consistent implementation across all UNIX platforms. Proctools' pkill and pgrep are preferable:

for procname; do
    pkill "$procname"
done

sleep 3
for procname; do
    # Why check if the process exists if you're just going to `SIGKILL` it?
    pkill -9 "$procname"
done

(Edit) If you have processes that are supposed to restart after being killed, you may not want to blindly kill them, so you can gather the PIDs first:

pids=()
for procname; do
    pids+=($(pgrep "$procname"))
done
# then proceed with `kill`

That said, you should really try to avoid using SIGKILL if you can. It does not give software a chance to clean up after itself. If a program won't quit shortly after receiving a SIGTERM it is probably waiting for something. Find out what it's waiting for (hardware interrupt? open file?) and fix that, and you can let it close cleanly.




回答2:


Without understanding what exactly the process does, I would say it probably isn't ideal cos you may have a situation where the processes you are killing are really doing some useful shutdown/cleanup work. Forcing it down with kill -9 may short-circuit that work and could cause corruption if your process is in fact writing data.

Assuming there is no danger of data corruption and it's ok to short-circuit the shutdown, can you just kill -9 the process the first time and be done with it. Do you have access to the developers of the process you are killing to understand what is going on that might prevent the shutdown from happening? The process might have blocked the INT and TERM for good reason.




回答3:


It is unlikely, but it is possible that in that 3 second wait, a new process could have taken over that PID and the second kill would kill it.



来源:https://stackoverflow.com/questions/11889425/automating-killall-then-killall-level-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!