Automating Killall then Killall level 9

2020-04-11 06:13发布

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?

3条回答
贼婆χ
2楼-- · 2020-04-11 06:44

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.

查看更多
混吃等死
3楼-- · 2020-04-11 06:48

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.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-04-11 06:51

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.

查看更多
登录 后发表回答