Execute a shell function with timeout

前端 未结 10 1117
死守一世寂寞
死守一世寂寞 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
    }
    

提交回复
热议问题