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

后端 未结 30 2421
悲哀的现实
悲哀的现实 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:35

    Trapping CHLD signal may not work because you can lose some signals if they arrived simultaneously.

    #!/bin/bash
    
    trap 'rm -f $tmpfile' EXIT
    
    tmpfile=$(mktemp)
    
    doCalculations() {
        echo start job $i...
        sleep $((RANDOM % 5)) 
        echo ...end job $i
        exit $((RANDOM % 10))
    }
    
    number_of_jobs=10
    
    for i in $( seq 1 $number_of_jobs )
    do
        ( trap "echo job$i : exit value : \$? >> $tmpfile" EXIT; doCalculations ) &
    done
    
    wait 
    
    i=0
    while read res; do
        echo "$res"
        let i++
    done < "$tmpfile"
    
    echo $i jobs done !!!
    

提交回复
热议问题