我有一个bash脚本启动一个子进程,它不时崩溃(实际上,挂起)并没有明显的原因(闭源,所以我无能为力).因此,我希望能够在给定的时间内启动此过程,如果在给定的时间后没有成功返回,则将其终止.
有没有一种简单而强大的方法来实现使用bash?
PS:告诉我这个问题是否更适合serverfault或超级用户.
Ign*_*ams 244
(如下所示: BASH FAQ条目#68:"如何运行命令,并在N秒后中止(超时)?")
如果您不介意下载某些内容,请使用timeout(sudo apt-get install timeout)并使用它:(大多数系统已安装它,否则使用sudo apt-get install coreutils)
timeout 10 ping www.goooooogle.com
Run Code Online (Sandbox Code Playgroud)
如果您不想下载某些内容,请执行内部超时操作:
( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping www.goooooogle.com )
Run Code Online (Sandbox Code Playgroud)
如果您想为更长的bash代码执行超时,请使用第二个选项:
( cmdpid=$BASHPID;
(sleep 10; kill $cmdpid) \
& while ! ping -w 1 www.goooooogle.com
do
echo crap;
done )
Run Code Online (Sandbox Code Playgroud)
Dan*_*Dan 26
# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) &
Run Code Online (Sandbox Code Playgroud)
或者获取退出代码:
# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) & waiter=$!
# wait on our worker process and return the exitcode
exitcode=$(wait $pid && echo $?)
# kill the waiter subshell, if it still runs
kill -9 $waiter 2>/dev/null
# 0 if we killed the waiter, cause that means the process finished before the waiter
finished_gracefully=$?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93106 次 |
| 最近记录: |