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

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

    I almost fell into the trap of using jobs -p to collect PIDs, which does not work if the child has already exited, as shown in the script below. The solution I picked was simply calling wait -n N times, where N is the number of children I have, which I happen to know deterministically.

    #!/usr/bin/env bash
    
    sleeper() {
        echo "Sleeper $1"
        sleep $2
        echo "Exiting $1"
        return $3
    }
    
    start_sleepers() {
        sleeper 1 1 0 &
        sleeper 2 2 $1 &
        sleeper 3 5 0 &
        sleeper 4 6 0 &
        sleep 4
    }
    
    echo "Using jobs"
    start_sleepers 1
    
    pids=( $(jobs -p) )
    
    echo "PIDS: ${pids[*]}"
    
    for pid in "${pids[@]}"; do
        wait "$pid"
        echo "Exit code $?"
    done
    
    echo "Clearing other children"
    wait -n; echo "Exit code $?"
    wait -n; echo "Exit code $?"
    
    echo "Waiting for N processes"
    start_sleepers 2
    
    for ignored in $(seq 1 4); do
        wait -n
        echo "Exit code $?"
    done
    

    Output:

    Using jobs
    Sleeper 1
    Sleeper 2
    Sleeper 3
    Sleeper 4
    Exiting 1
    Exiting 2
    PIDS: 56496 56497
    Exiting 3
    Exit code 0
    Exiting 4
    Exit code 0
    Clearing other children
    Exit code 0
    Exit code 1
    Waiting for N processes
    Sleeper 1
    Sleeper 2
    Sleeper 3
    Sleeper 4
    Exiting 1
    Exiting 2
    Exit code 0
    Exit code 2
    Exiting 3
    Exit code 0
    Exiting 4
    Exit code 0
    

提交回复
热议问题