【问题标题】:How can I check the exit status of multiple processes in background in loop?如何在循环中检查后台多个进程的退出状态?
【发布时间】:2013-04-16 08:18:04
【问题描述】:

我在后台有一个带有脚本的循环

while read host
do
./script &
done
wait  #waits till all the background processes are finished

但我想检查进程的退出状态我该怎么做

while read host
do
./script &
wait $! || let "FAIL+=1"
done
wait
echo $fail

但是上面的代码会并行执行,因为时间是一个重要因素 对我来说,所以我想为所有主机并行执行。

这是否可以知道哪个进程失败以便我可以做

   echo "these are the list of process ids in background that failed"
   12346
   43561
   .....

对于可以在后台运行的并行进程的数量是否有任何限制。 在上述循环中运行大约 20 个并行进程是否安全

【问题讨论】:

  • 如果您使用 Bash,您可以将进程 ID 存储到一个数组中,然后使用循环检查哪些进程仍在运行,可能通过 'kill -s 0 '。跨度>
  • 是的,我知道我能做到这一点:-)

标签: linux bash shell process


【解决方案1】:

您可以将其添加到脚本的末尾:

RC=$?
test $RC -eq 0 || echo "$$ failed"
exit $RC

$$ 返回 shell 的 PID。您的后台脚本将在各自独立的 shell 中运行。

exit $RC 行显然是可选的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    相关资源
    最近更新 更多