是否有可能设置时间从bash脚本? [英] Is it possible to set time out from bash script?
问题描述
有时我的bash脚本都挂按住没有明确的理由。
Sometimes my bash scripts are hanging and hold without clear reason
因此,他们居然能挂到永远(脚本程序将运行,直到我杀了它)
So they actually can hang for ever ( script process will run until I kill it )
是否有可能从程序例如半小时后,在bash脚本超时机制结合起来,以出口?
Is it possible to combine in the bash script time out mechanism in order to exit from the program after for example ½ hour?
推荐答案
这仅击的方法通过运行一个函数作为后台作业执行超时封装脚本里面所有的超时code:
This Bash-only approach encapsulates all the timeout code inside your script by running a function as a background job to enforce the timeout:
#!/bin/bash
Timeout=1800 # 30 minutes
function timeout_monitor() {
sleep "$Timeout"
kill "$1"
}
# start the timeout monitor in
# background and pass the PID:
timeout_monitor "$$" &
Timeout_monitor_pid=$!
# <your script here>
# kill timeout monitor when terminating:
kill "$Timeout_monitor_pid"
请注意,该功能将在单独的进程中执行。因此,监控进程的PID( $
)必须通过。我离开了通常的参数检查简洁起见。
Note that the function will be executed in a separate process. Therefore the PID of the monitored process ($$
) must be passed. I left out the usual parameter checking for the sake of brevity.
这篇关于是否有可能设置时间从bash脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!