在Bash中给定超时后如何杀死子进程? [英] How to kill a child process after a given timeout in Bash?
问题描述
我有一个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 FAQ条目#68:我如何运行命令,并在N秒后中止(超时)? ")
(As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")
如果您不介意下载某些内容,请使用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
如果您不想下载某些内容,请执行内部超时操作:
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中给定超时后如何杀死子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!