How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

后端 未结 30 2408
悲哀的现实
悲哀的现实 2020-11-22 03:50

How to wait in a bash script for several subprocesses spawned from that script to finish and return exit code !=0 when any of the subprocesses ends with code !=0 ?

S

30条回答
  •  北海茫月
    2020-11-22 04:25

    I used this recently (thanks to Alnitak):

    #!/bin/bash
    # activate child monitoring
    set -o monitor
    
    # locking subprocess
    (while true; do sleep 0.001; done) &
    pid=$!
    
    # count, and kill when all done
    c=0
    function kill_on_count() {
        # you could kill on whatever criterion you wish for
        # I just counted to simulate bash's wait with no args
        [ $c -eq 9 ] && kill $pid
        c=$((c+1))
        echo -n '.' # async feedback (but you don't know which one)
    }
    trap "kill_on_count" CHLD
    
    function save_status() {
        local i=$1;
        local rc=$2;
        # do whatever, and here you know which one stopped
        # but remember, you're called from a subshell
        # so vars have their values at fork time
    }
    
    # care must be taken not to spawn more than one child per loop
    # e.g don't use `seq 0 9` here!
    for i in {0..9}; do
        (doCalculations $i; save_status $i $?) &
    done
    
    # wait for locking subprocess to be killed
    wait $pid
    echo
    

    From there one can easily extrapolate, and have a trigger (touch a file, send a signal) and change the counting criteria (count files touched, or whatever) to respond to that trigger. Or if you just want 'any' non zero rc, just kill the lock from save_status.

提交回复
热议问题