How to wait in bash for several subprocesses to fi

2018-12-31 08:42发布

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 ?

Simple script:

#!/bin/bash
for i in `seq 0 9`; do
  doCalculations $i &
done
wait

The above script will wait for all 10 spawned subprocesses, but it will always give exit status 0 (see help wait). How can I modify this script so it will discover exit statuses of spawned subprocesses and return exit code 1 when any of subprocesses ends with code !=0?

Is there any better solution for that than collecting PIDs of the subprocesses, wait for them in order and sum exit statuses?

27条回答
春风洒进眼中
2楼-- · 2018-12-31 09:26

I'm thinking maybe run doCalculations; echo "$?" >>/tmp/acc in a subshell that is sent to the background, then the wait, then /tmp/acc would contain the exit statuses, one per line. I don't know about any consequences of the multiple processes appending to the accumulator file, though.

Here's a trial of this suggestion:

File: doCalcualtions

#!/bin/sh

random -e 20
sleep $?
random -e 10

File: try

#!/bin/sh

rm /tmp/acc

for i in $( seq 0 20 ) 
do
        ( ./doCalculations "$i"; echo "$?" >>/tmp/acc ) &
done

wait

cat /tmp/acc | fmt
rm /tmp/acc

Output of running ./try

5 1 9 6 8 1 2 0 9 6 5 9 6 0 0 4 9 5 5 9 8
查看更多
余生无你
3楼-- · 2018-12-31 09:27
set -e
fail () {
    touch .failure
}
expect () {
    wait
    if [ -f .failure ]; then
        rm -f .failure
        exit 1
    fi
}

sleep 2 || fail &
sleep 2 && false || fail &
sleep 2 || fail
expect

The set -e at top makes your script stop on failure.

expect will return 1 if any subjob failed.

查看更多
栀子花@的思念
4楼-- · 2018-12-31 09:28

The following code will wait for completion of all calculations and return exit status 1 if any of doCalculations fails.

#!/bin/bash
for i in $(seq 0 9); do
   (doCalculations $i >&2 & wait %1; echo $?) &
done | grep -qv 0 && exit 1
查看更多
登录 后发表回答