bash shutdown hook;或者,在主进程被终止时终止所有后台进程

时间:2013-08-16 18:05:01

标签: bash process

我有一个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变量中列出的所有后台进程。

我该怎么做?

如果有可能在主进程上捕获kill信号并在发生这种情况时执行一个函数(shutdown hook),我会做类似的事情:

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

但是我找不到怎么做......

3 个答案:

答案 0 :(得分:12)

这是一个不需要您跟踪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

跑步时,我们会看到三个小组负责人的小费,然后看到他们被杀:

$ ./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

答案 1 :(得分: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/

答案 2 :(得分:0)

kill `ps axl | grep "endlesscommand" | awk '{printf $4" "}'`

这将查找影响“endlesscommand”

的父进程