我有一个我正在运行的主脚本,从中我有第二个“慢进程”我想开始,并且如果在时间限制内没有完成,则在主脚本中“做一些事情” – 取决于如果它完成了.注:如果“慢速过程”在我的时间限制之前结束,我不想要等待整个时间限制.
我希望“缓慢的过程”继续前进,这样我就可以收集关于它的性能的统计数据和取证.
我已经研究过使用timeout,但是在完成后会杀死我的脚本.
假设这个简化的例子.
main.sh
result=`timeout 3 ./slowprocess.sh`
if [ "$result" = "Complete" ]
then
echo "Cool it completed, do stuff..."
else
echo "It didn't complete, do something else..."
fi
slowprocess.sh
#!/bin/bash
start=`date +%s`
sleep 5
end=`date +%s`
total=`expr $end - $start`
echo $total >> /tmp/performance.log
echo "Complete"
在这里,它使用超时 – 所以脚本死了,所以在/tmp/performance.log中没有结束 – 我希望slowprocess.sh完成,但是,我希望main.sh进入下一步,即使它没有在3秒钟内完成.
解决方法:
使用ksh / bash / zsh:
{
(./slowprocess.sh >&3 3>&-; echo "$?") |
if read -t 3 status; then
echo "Cool it completed with status $status, do stuff..."
else
echo "It didn't complete, do something else..."
fi
} 3>&1
我们将原始标准输出复制到fd 3(3>& 1),因此我们可以将其恢复为slowprocess.sh(>& 3),而其余(…)子shell的stdout转到管道读-t 3.
或者,如果你想使用超时(这里假设GNU超时):
timeout --foreground 3 sh -c './slowprocess.sh;:'
将避免slowprocess.sh被杀死(对于通过在shell进程中执行最后一个命令进行优化的sh实现,;:).
标签:bash,linux,timeout,kill
来源: https://codeday.me/bug/20190812/1644002.html