问题描述
我有一个 bash 脚本,它启动一个子进程,该进程不时崩溃(实际上,挂起)并且没有明显的原因(封闭源代码,所以我无能为力).因此,我希望能够在给定的时间内启动此进程,如果在给定的时间后没有成功返回,则将其终止.
I have a bash script that launches a child process that crashes (actually, hangs) from time to time and with no apparent reason (closed source, so there isn't much I can do about it). As a result, I would like to be able to launch this process for a given amount of time, and kill it if it did not return successfully after a given amount of time.
是否有一种简单和强大的方法来使用 bash 实现这一目标?
Is there a simple and robust way to achieve that using bash?
P.S.:告诉我这个问题更适合 serverfault 还是超级用户.
P.S.: tell me if this question is better suited to serverfault or superuser.
推荐答案
(见:BASH 常见问题条目 #68:如何运行命令,并让它在 N 秒后中止(超时)?")
如果您不介意下载某些东西,请使用 timeout
(sudo apt-get install timeout
) 并使用它:(大多数系统已经安装了它,否则使用sudo apt-get install coreutils
)
If you don't mind downloading something, use timeout
(sudo apt-get install timeout
) and use it like: (most Systems have it already installed otherwise use sudo apt-get install coreutils
)
timeout 10 ping www.goooooogle.com
如果您不想下载某些内容,请执行 timeout 在内部执行的操作:
If you don't want to download something, do what timeout does internally:
( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping www.goooooogle.com )
如果您想为更长的 bash 代码设置超时,请使用第二个选项:
In case that you want to do a timeout for longer bash code, use the second option as such:
( cmdpid=$BASHPID;
(sleep 10; kill $cmdpid)
& while ! ping -w 1 www.goooooogle.com
do
echo crap;
done )
这篇关于如何在 Bash 中给定超时后杀死子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!