11

我有一个 bash 作为后台进程运行无尽的命令:

#!/bin/bash

function xyz() {
  # some awk command
}

endlesscommand "param 1" | xyz &  # async
pids=$!
endlesscommand "param 2" | xyz &  # async
pids="$pids "$!
endlesscommand "param 3" | xyz    # sync so the script doesn't leave

停止此脚本的唯一方法是(必须是)Ctrl-C 或 kill,当发生这种情况时,我需要终止 $pids 变量中列出的所有后台进程。

我怎么做?

如果可以在主进程上捕获终止信号并在发生这种情况时执行一个函数(关闭挂钩),我会执行以下操作:

for $pid in $pids; do kill $pid; done;

但我找不到如何做到这一点......

4

3 回答 3

13

这是一个不需要您跟踪的陷阱pids

trap 'jobs -p | xargs kill' EXIT

编辑:@Barmar 询问这是否适用于非源脚本,其中作业控制通常不可用。确实如此。考虑这个脚本:

$ cat no-job-control
#! /bin/bash

set -e -o pipefail

# Prove job control is off
if suspend
then
  echo suspended
else
  echo suspension failed, job control must be off
fi

echo

# Set up the trap
trap 'jobs -p | xargs kill' EXIT

# Make some work
(echo '=> Starting 0'; sleep 5; echo '=> Finishing 0') &
(echo '=> Starting 1'; sleep 5; echo '=> Finishing 1') &
(echo '=> Starting 2'; sleep 5; echo '=> Finishing 2') &

echo "What's in jobs -p?"
echo

jobs -p

echo
echo "Ok, exiting now"
echo

运行时,我们看到三个组长的 pid,然后看到他们被杀死:

$ ./no-job-control
./no-job-control: line 6: suspend: cannot suspend: no job control
suspension failed, job control must be off

=> Starting 0
What's in jobs -p?
=> Starting 1

54098
54099
54100

Ok, exiting now

=> Starting 2
./no-job-control: line 31: 54098 Terminated: 15          ( echo '=> Starting 0'; sleep 5; echo '=> Finishing 0' )
./no-job-control: line 31: 54099 Terminated: 15          ( echo '=> Starting 1'; sleep 5; echo '=> Finishing 1' )
./no-job-control: line 31: 54100 Terminated: 15          ( echo '=> Starting 2'; sleep 5; echo '=> Finishing 2' )

如果我们改为注释掉该trap行并重新运行,这三个作业不会死掉,实际上会在几秒钟后打印出它们的最终消息。注意返回的提示与最终输出交错。

$ ./no-job-control
./no-job-control: line 6: suspend: cannot suspend: no job control
suspension failed, job control must be off

=> Starting 0
What's in jobs -p?

54110
54111
54112
=> Starting 1

Ok, exiting now

=> Starting 2
$ => Finishing 0
=> Finishing 2
=> Finishing 1
于 2013-08-16T18:52:45.693 回答
1

您可以使用 pgrep 和一个函数来杀死在主进程下创建的所有进程,就像这样。这不仅会杀死直接子进程,还会杀死在其下创建的子进程。

#!/bin/bash

function killchildren {
    local LIST=() IFS=$'\n' A
    read -a LIST -d '' < <(exec pgrep -P "$1")
    local A SIGNAL="${2:-SIGTERM}"
    for A in "${LIST[@]}"; do
        killchildren_ "$A" "$SIGNAL"
    done
}

function killchildren_ {
    local LIST=()
    read -a LIST -d '' < <(exec pgrep -P "$1")
    kill -s "$2" "$1"
    if [[ ${#LIST[@]} -gt 0 ]]; then
        local A
        for A in "${LIST[@]}"; do
            killchildren_ "$A" "$2"
        done
    fi
}

trap 'killchildren "$BASHPID"' EXIT

endlesscommand "param 1" &
endlesscommand "param 2" &
endlesscommand "param 3" &

while pgrep -P "$BASHPID" >/dev/null; do
    wait
done

至于您的原始代码,最好只使用数组,并且您也不需要使用 for 循环:

#!/bin/bash

trap 'kill "${pids[@]}"' EXIT

pids=()
endlesscommand "param 1" &  # async
pids+=("$!")
endlesscommand "param 2" &  # async
pids+=("$!")
endlesscommand "param 3" &  # syncing this is not a good idea since if the main process would end along with it if it ends earlier.
pids+=("$!")

while pgrep -P "$BASHPID" >/dev/null; do
    wait
done

原函数参考:http ://www.linuxquestions.org/questions/blog/konsolebox-210384/bash-functions-to-list-and-kill-or-send-signals-to-process-trees-34624/

于 2013-08-16T19:21:17.717 回答
0
kill `ps axl | grep "endlesscommand" | awk '{printf $4" "}'`

这将寻找影响“endlesscommand”的父进程

于 2013-08-16T18:08:44.530 回答