Execute a shell function with timeout

前端 未结 10 1083
死守一世寂寞
死守一世寂寞 2020-12-01 00:40

Why would this work

timeout 10s echo \"foo bar\" # foo bar

but this wouldn\'t

function echoFooBar {
  echo \"foo bar\"
}

e         


        
相关标签:
10条回答
  • 2020-12-01 01:16

    This function uses only builtins

    • Maybe consider evaling "$*" instead of running $@ directly depending on your needs

    • It starts a job with the command string specified after the first arg that is the timeout value and monitors the job pid

    • It checks every 1 seconds, bash supports timeouts down to 0.01 so that can be tweaked

    • Also if your script needs stdin, read should rely on a dedicated fd (exec {tofd}<> <(:))

    • Also you might want to tweak the kill signal (the one inside the loop) which is default to -15, you might want -9

    ## forking is evil
    timeout() {
        to=$1; shift
        $@ & local wp=$! start=0
         while kill -0 $wp; do
            read -t 1
            start=$((start+1))
            if [ $start -ge $to ]; then
                kill $wp && break
            fi
        done
    }
    
    0 讨论(0)
  • 2020-12-01 01:18

    This one liner will exit your Bash session after 10s

    $ TMOUT=10 && echo "foo bar"
    
    0 讨论(0)
  • 2020-12-01 01:25

    There's an inline alternative also launching a subprocess of bash shell:

    
    timeout 10s bash <<EOT
    function echoFooBar {
      echo foo
    }
    
    echoFooBar
    sleep 20
    EOT
    
    
    0 讨论(0)
  • 2020-12-01 01:26

    timeout is a command - so it is executing in a subprocess of your bash shell. Therefore it has no access to your functions defined in your current shell.

    The command timeout is given is executed as a subprocess of timeout - a grand-child process of your shell.

    You might be confused because echo is both a shell built-in and a separate command.

    What you can do is put your function in it's own script file, chmod it to be executable, then execute it with timeout.

    Alternatively fork, executing your function in a sub-shell - and in the original process, monitor the progress, killing the subprocess if it takes too long.

    0 讨论(0)
提交回复
热议问题