我正在脚本中运行几个后台进程
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
作为后台进程运行--但它变得越来越笨拙。
你能帮帮我吗?
发布于 2016-05-28 15:29:34
以下脚本监视测试子进程(在本例中为sleep+false和sleep+true),并报告它们的PID和退出代码:
#!/bin/bash
set -m
trap myhandler CHLD
myhandler() {
echo sigchld received
cat /tmp/foo
}
( sleep 5; false; echo "exit p1=$?" ) > /tmp/foo &
p1=$!
echo "p1=$p1"
( sleep 3; true; echo "exit p2=$?" ) > /tmp/foo &
p2=$!
echo "p2=$p2"
pstree -p $$
wait
结果是:
p1=3197
p2=3198
prueba(3196)─┬─prueba(3197)───sleep(3199)
├─prueba(3198)───sleep(3201)
└─pstree(3200)
sigchld received
sigchld received
exit p2=0
sigchld received
exit p1=1
使用SIGUSR1
而不是SIGCHLD
可能很有趣;参见这里的示例:https://stackoverflow.com/a/12751700/4886927。
此外,在陷阱处理程序中,可以确定哪个子程序仍然活着。类似于:
myhandler() {
if kill -0 $p1; then
echo "child1 is alive"
fi
if kill -0 $p2; then
echo "child2 is alive"
fi
}
或者在其中一个孩子死后杀了两个孩子:
myhandler() {
if kill -0 $p1 && kill -0 $p2; then
echo "all childs alive"
else
kill -9 $p1 $p2
fi
}
https://stackoverflow.com/questions/37496896
复制相似问题