简体   繁体   English

Bash等待多个并发子进程并杀死所有错误

[英]Bash wait for several simultaneous subprocesses and kill all on error

I'm running a bash script with multiple simultaneous commands (python scripts). 我正在运行具有多个同时命令(Python脚本)的bash脚本。 I'm trying to kill all the processes if one of them has failed. 如果其中一个失败,我将尝试杀死所有进程。 The thing is that the python scripts are still running in the background, and if one of them has failed, my bash script doesn't know about. 事实是,python脚本仍在后台运行,并且如果其中一个失败,我的bash脚本也不知道。

Here's a snippet from my script: 这是我脚本的一个片段:

set -a
trap cleanup_children SIGTERM
MY_PID=$$

function thread_listener () {
    to_execute="$1"
    echo "Executing $to_execute ..."
    $to_execute &
    PID=$!
    trap 'echo killing $PID; kill $PID' SIGTERM
    echo "Waiting for $PID ($to_execute) ..."
    wait $PID || if `kill -0 $MY_PID &> /dev/null`; then kill $MY_PID; fi
}

function cleanup_children () {
    for job in `jobs -p`
    do
        if `kill -0 $job &> /dev/null`; then
            echo "Killing child number $job"
            ps -p $job
            kill $job
        fi
    done
}

function create_app1 () {
    cd ${GIT_DIR}
    python ./create-app.py -myapp
    exit_code=$?
    echo "Create app1 ISO result: ${exit_code}"
    [ "${exit_code}" == "1" ] && exit 1
    mv ${ISO_OUTPUT_DIR}/rhel-7.1.iso ${ISO_OUTPUT_DIR}/${ISO_NAME}.iso
}

function create_app2 () {
    cd ${GIT_DIR}
    python ./create-app.py -do-something
    exit_code=$?
    echo "Create app1 ISO result: ${exit_code}"
    [ "${exit_code}" == "1" ] && exit 1
    mv ${ISO_OUTPUT_DIR}/rhel-7.1.iso ${ISO_OUTPUT_DIR}/${ISO_NAME}.iso
}

export -f create_app1
export -f create_app2

echo "MY_PID=$MY_PID"
thread_listener create_app1 &
PID_APP1=$!

thread_listener create_app2 &
PID_APP2=$!
wait

kill $PID_APP1 2> /dev/null
kill $PID_APP2 2> /dev/null

Hm, this looks quite advanced ;). 嗯,这看起来相当先进;)。 Do I assume correctly that you never see the "Create app1 ISO result" output then because the python script does not terminate? 我是否正确假设您因为python脚本未终止而再也看不到“创建app1 ISO结果”输出? It might be an issue with the signal not being properly dispatched to bash background jobs. 信号未正确分配给bash后台作业可能是一个问题。 It might also be related to your python code not properly reacting to the signal. 这也可能与您的python代码对信号没有正确反应有关。 Have you checked out https://docs.python.org/2/library/signal.html ? 您是否签出了https://docs.python.org/2/library/signal.html Sure you'd have to figure out the exact steps how to interrupt you python code while executing. 当然,您必须找出执行步骤时如何中断python代码的确切步骤。 I'd suggest to first make sure that the python code reacts to signals the way you want. 我建议首先确保python代码以您想要的方式对信号做出反应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM