为什么此kill在此Bash脚本中不起作用,而仅在脚本之外起作用?

时间:2018-07-03 20:09:29

标签: bash shell sh kill

以下是一个人为设计的示例,该示例演示了该效果并且必须使用root运行。它会在后台执行ping进程并尝试将其杀死。

#!/bin/bash

# Ensure that there is no ping process before we begin.
killall ping

sudo ping google.com > /dev/null &
PID=$!

sleep 0.5

kill $PID
echo "Exit code of kill $PID: $?"

# Check the running ping processes. There should be no ping
# process if the above `kill $PID` worked correctly.
ps aux | grep -v grep | grep ping

但是,即使kill的返回代码为0,该脚本也无法终止该进程。以下是示例输出。

$ bash test.sh
Exit code of kill 16516: 0
root     16516  0.0  0.0  14956  2212 pts/2    S    13:22   0:00 sudo ping google.com
root     16518  1.0  0.0  13112  1292 pts/2    S    13:22   0:00 ping google.com

我注意到,如果我取出sudo,它将被正确杀死。为什么会这样呢?我怀疑sudo的子进程以某种方式将其弄乱了。

更新1:

更奇怪。如果我在脚本后执行相同的kill命令,它将起作用。

$ bash test.sh
Exit code of kill 16631: 0
root     16631  3.0  0.0  14956  2212 pts/2    S    13:29   0:00 sudo ping google.com
root     16633  0.0  0.0  13112  1292 pts/2    S    13:29   0:00 ping google.com
$ ps aux | grep -v grep | grep ping
root     16631  0.5  0.0  14956  2212 pts/2    S    13:29   0:00 sudo ping google.com
root     16633  0.0  0.0  13112  1292 pts/2    S    13:29   0:00 ping google.com
$ kill 16631
$ ps aux | grep -v grep | grep ping
$
$ kill 16631
-bash: kill: (16631) - No such process
$

1 个答案:

答案 0 :(得分:4)

之所以会这样,是因为控制sudo进程不会传播来自其自身进程组(source)的信号:

/*
 * Do not forward signals sent by a process in the command's process
 * group, as we don't want the command to indirectly kill itself.
 * For example, this can happen with some versions of reboot that
 * call kill(-1, SIGTERM) to kill all other processes.
 */
if (USER_SIGNALED(sc->siginfo) && sc->siginfo->si_pid != 0) {
    pid_t si_pgrp = getpgid(sc->siginfo->si_pid);
    if (si_pgrp != -1) {
    if (si_pgrp == ec->ppgrp || si_pgrp == ec->cmnd_pid)
        debug_return;
    } else if (sc->siginfo->si_pid == ec->cmnd_pid) {
        debug_return;
    }
}

在脚本外执行命令时,可以在单独的进程组中运行它,以便中继信号。