后台子进程的 pid 存储在 $! 中。
您可以将所有子进程的 pid 存储到一个数组中,例如PIDS[]。
wait [-n] [jobspec or pid …]
等到每个进程 ID pid 或作业规范 jobspec 指定的子进程退出,并返回最后等待的命令的退出状态。如果给出了作业规范,则等待作业中的所有进程。如果没有给出参数,则等待所有当前活动的子进程,并且返回状态为零。如果提供了 -n 选项,wait 将等待任何作业终止并返回其退出状态。如果 jobspec 和 pid 都没有指定 shell 的活动子进程,则返回状态为 127。
使用wait命令可以等待所有子进程完成,同时可以通过$?获取每个子进程的退出状态,并将状态存入STATUS []。然后你可以根据状态做一些事情。
我尝试了以下 2 种解决方案,它们运行良好。 solution01 是
更简洁,而 solution02 有点复杂。
解决方案01
#!/bin/bash
# start 3 child processes concurrently, and store each pid into array PIDS[].
process=(a.sh b.sh c.sh)
for app in ${process[@]}; do
./${app} &
PIDS+=($!)
done
# wait for all processes to finish, and store each process's exit code into array STATUS[].
for pid in ${PIDS[@]}; do
echo "pid=${pid}"
wait ${pid}
STATUS+=($?)
done
# after all processed finish, check their exit codes in STATUS[].
i=0
for st in ${STATUS[@]}; do
if [[ ${st} -ne 0 ]]; then
echo "$i failed"
else
echo "$i finish"
fi
((i+=1))
done
解决方案02
#!/bin/bash
# start 3 child processes concurrently, and store each pid into array PIDS[].
i=0
process=(a.sh b.sh c.sh)
for app in ${process[@]}; do
./${app} &
pid=$!
PIDS[$i]=${pid}
((i+=1))
done
# wait for all processes to finish, and store each process's exit code into array STATUS[].
i=0
for pid in ${PIDS[@]}; do
echo "pid=${pid}"
wait ${pid}
STATUS[$i]=$?
((i+=1))
done
# after all processed finish, check their exit codes in STATUS[].
i=0
for st in ${STATUS[@]}; do
if [[ ${st} -ne 0 ]]; then
echo "$i failed"
else
echo "$i finish"
fi
((i+=1))
done