使用 bash 运行脚本并提供终止时间

Wel*_*lls 6 bash

是否可以从 bash(例如 python)运行具有终止时间的脚本,这意味着如果该脚本运行时间超过 X 秒,则终止它?

C0d*_*lus 5

是的,可以运行一个 bash 脚本,但它的终止超时。你可以这样做:

1.使用超时

它运行一个有时间限制的命令。一般语法包括:

timeout signal duration command/script arguments
Run Code Online (Sandbox Code Playgroud)

在哪里 :

  • 信号是信号名称或相应的编号。见man 7 信号
  • 持续时间是以数字为后缀指定的超时s时间,例如秒、m分钟、h小时、d天。
  • 默认为秒,当您只指定一个数字时。例如,您想在 2 分钟后终止脚本,然后:

    timeout 2m /path/to/script arg1 arg2
    
    Run Code Online (Sandbox Code Playgroud)
  • NOTE:默认超时信号SIGTERM用于某些进程不终止。在这种情况下,我们需要使用SIGKILL信号来终止进程。

        timeout -s KILL 2m /path/to/script arg1 arg2
    
    Run Code Online (Sandbox Code Playgroud)

    或者

        timeout -k 30 2m /path/to/slow-command arg1 arg2
    
    Run Code Online (Sandbox Code Playgroud)

    在这种情况下, timeoutSIGTERM在初始超时 2 分钟后首先发送信号。然后,等待 30 秒的另一个超时,SIGKILL如果它仍在运行,则向该进程发送。

2.我没有timeout命令:

好吧,有很多替代方法或解决方法,如果由于某种原因您无法使用timeout. 这些是 :

  1. 条件sleep然后kill

       /path/to/script arg1 arg2 & sleep 2m ; kill $!
    
    Run Code Online (Sandbox Code Playgroud)
  2. Perl 警报(这可以在顺序脚本中使用。):

       perl -e "alarm 120; exec @ARGV" "/path/to/script arg1 arg2"
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用期望命令:

       time_out=120
       command="/path/to/script arg1 arg2"
    
       expect -c " set echo \"-noecho\";
                   set timeout $time_out;
                   spawn -noecho $command;
                   expect timeout { exit 1 } eof { exit 0 } "
    
    Run Code Online (Sandbox Code Playgroud)

随意添加更多详细信息。