是否可以从 bash 脚本中设置超时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28927783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:30:20  来源:igfitidea点击:

Is it possible to set time out from bash script?

linuxbashprocesssettimeout

提问by maihabunash

Sometimes my bash scripts are hanging and hold without clear reason

有时我的 bash 脚本没有明确的原因就挂了

So they actually can hang for ever ( script process will run until I kill it )

所以他们实际上可以永远挂起(脚本进程会一直运行直到我杀死它)

Is it possible to combine in the bash script time out mechanism in order to exit from the program after for example ? hour?

是否可以结合 bash 脚本超时机制,以便在例如之后退出程序?小时?

回答by rici

If you have Gnu coreutils, you can use the timeoutcommand:

如果您有 Gnu coreutils,则可以使用以下timeout命令:

timeout 1800s ./myscript

To check if the timeout occurred check the status code:

要检查是否发生超时,请检查状态代码:

timeout 1800s ./myscript

if (($? == 124)); then
  echo "./myscript timed out after 30 minutes" >>/path/to/logfile
  exit 124
fi

回答by Michael Jaros

This Bash-only approach encapsulates all the timeout code inside your script by running a function as a background job to enforce the timeout:

这种 Bash-only 方法通过运行一个函数作为后台作业来强制超时,将所有超时代码封装在脚本中:

#!/bin/bash

Timeout=1800 # 30 minutes

function timeout_monitor() {
   sleep "$Timeout"
   kill ""
}

# 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"

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.

请注意,该函数将在单独的进程中执行。因此$$必须传递被监视进程的PID ( )。为简洁起见,我省略了通常的参数检查。