【发布时间】:2016-09-26 14:02:57
【问题描述】:
我在我的脚本中运行了几个后台进程
run_gui()
{
exec ... # the real commands here
}
run_ai1(), run_ai2 的函数是类似的。
然后我运行函数并做所需的管道
run_gui &
run_ai1 &
run_ai2 &
while true; do
while true; do
read -u $ai1_outfd line || echo "Nothing read"
if [[ $line ]]; then
: # processing
fi
done
sleep $turndelay
while true; do
read -u $ai2_outfd line || echo "nothing read"
if [[ $line ]]; then
: # processing
fi
done
sleep $turndelay
done
如果这三个进程中的任何一个退出,我想检查它们的退出代码并终止其余进程。例如,如果run_ai2 以退出代码 3 退出,那么我想停止进程 run_ai1 和 run_gui 并以退出代码 1 退出主脚本。不同背景进程的正确退出代码可能会有所不同。
问题是:我怎样才能检测到它?有命令wait,但我事先不知道哪个脚本会先完成。我可以将 wait 作为后台进程运行 - 但它变得更加笨拙。
你能帮帮我吗?
【问题讨论】:
-
trap SIGCHLD,它允许在子端执行一些语句
-
你能用Expect吗?在 Expect 中捕获退出的子进程比 POSIX shell 或 Bash 更优雅。
-
@nwk 我应该写一个 bash 脚本。所以我怀疑这是否会被允许。
-
@pasabaporaqui 无论我尝试如何捕获
SIGCHLD,都与我在此处描述的相去甚远。进程要么根本不退出(也不对 SIGINT 做出反应),要么过早退出。
标签: bash background-process pid