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

后端 未结 30 2418
悲哀的现实
悲哀的现实 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:37

    wait also (optionally) takes the PID of the process to wait for, and with $! you get the PID of the last command launched in background. Modify the loop to store the PID of each spawned sub-process into an array, and then loop again waiting on each PID.

    # run processes and store pids in array
    for i in $n_procs; do
        ./procs[${i}] &
        pids[${i}]=$!
    done
    
    # wait for all pids
    for pid in ${pids[*]}; do
        wait $pid
    done
    

提交回复
热议问题