如何获取bash中多个并行后台进程的退出状态 [英] How to get the exit status of multiple parallel background processes in bash

查看:88
本文介绍了如何获取bash中多个并行后台进程的退出状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Bash中,我想并行调用多个命令,同时捕获所有进程的退出代码.

In Bash, I want to call a command multiple times in parallel, while capturing all the processes exit codes.

我知道如何启动并等待它们,但是等待只会给我最后退出的进程的退出代码.我还需要寿命较短的退出代码.

I know how to start and wait for them, but wait will only give me the exit code of the last process exiting. I also need the exit code of the shorter lived processes.

不幸的是,我没有bash 4.3,所以 wait -n 不是一个选项,也不像

Unfortunately I don't have bash 4.3, so wait -n is not an option, nor is gnu parallel as suggested in #3004811

#16032001 几乎问了同样的问题,但那里也没有提供解决方案.

#16032001 pretty much asks the same question but no solution was offered there either.

我目前唯一想到的方法是编写一个帮助程序脚本,将退出代码存储在文件中,但这听起来并不干净.

The only way I can currently think of is writing a helper script that stores the exit codes in a file, but this doesn't sound like a clean solution.

推荐答案

答案在我没有意识到,尽管孩子立即被bash收割,但是内置的等待仍然可以访问该pid的退出代码.

I was unaware that though the child is immediately reaped by bash, the builtin wait can still access the exit code for the pid.

#!/bin/bash

FAIL=0
PIDS=""

echo "starting"

sleep 5 &
PIDS="$PIDS $!"

sleep 3 &
PIDS="$PIDS $!"

/bin/false &
PIDS="$PIDS $!"

sleep 3 &
PIDS="$PIDS $!"

for job in $PIDS
do
    wait $job || let "FAIL+=1"
    echo $job $FAIL
done

echo $FAIL

if [ "$FAIL" == "0" ];
then
    echo "YAY!"
else
    echo "FAIL! ($FAIL)"
fi

正确给出

starting
14772 0
14773 0
14774 1
14775 1
1
FAIL! (1)

只有第三个进程(/bin/false)失败,这在第三行中从0到1的切换表示.

Only the third process (/bin/false) fails, indicated by the switch from 0 to one in the third line.

这篇关于如何获取bash中多个并行后台进程的退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆