当任何子进程以代码 !=0 结束时,如何在 bash 中等待多个子进程完成并返回退出代码 !=0?
如何在 bash 脚本中等待从该脚本产生的多个子进程完成并在任何子进程以代码 !=0 结束时返回退出代码 !=0 ?
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 ?
简单的脚本:
#!/bin/bash
for i in `seq 0 9`; do
doCalculations $i &
done
wait
上面的脚本将等待所有 10 个生成的子进程,但它总是给出退出状态 0(参见 help wait
).如何修改此脚本,以便在任何子进程以代码 !=0 结束时发现生成的子进程的退出状态并返回退出代码 1?
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?
有没有比收集子进程的PID,按顺序等待它们并总结退出状态更好的解决方案?
Is there any better solution for that than collecting PIDs of the subprocesses, wait for them in order and sum exit statuses?
wait
还(可选)获取要等待的进程的 PID
,并使用 $!
你会得到在后台启动的最后一个命令的 PID
.修改循环,将每个生成的子进程的 PID
存储到一个数组中,然后再次循环等待每个 PID
.
wait
also (optionally) takes the PID
of the process to wait for, and with $!
you get the PID
of the last command launched in the 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