3

有时我想要killall某个进程,但运行killall不起作用。因此,当我尝试再次启动该过程时,它会失败,因为上一个会话仍在运行。然后我不得不乏味地运行killall -9它。所以为了简化我的生活,我创建了一个realkill脚本,它是这样的:

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.

那么,这是最好的方法吗?我可以通过哪些方式改进此脚本?

4

3 回答 3

5

killall如果可以,请避免,因为在所有 UNIX 平台上没有一致的实现。Proctools pkillpgrep更可取:

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

(编辑)如果您有应该在被杀死后重新启动的进程,您可能不想盲目地杀死它们,因此您可以先收集 PID:

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

也就是说,如果可以的话,你真的应该尽量避免使用SIGKILL。它不会让软件有机会自行清理。如果程序在收到 a 后不会立即退出,SIGTERM则它可能正在等待某些东西。找出它在等待什么(硬件中断?打开文件?)并修复它,你可以让它干净地关闭。

于 2012-08-09T18:13:38.917 回答
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.

于 2012-08-09T18:16:33.850 回答
2

这不太可能,但有可能在这 3 秒的等待中,一个新进程可能已经接管了该 PID,并且第二次 kill 将杀死它。

于 2012-08-09T19:05:28.653 回答