用超时执行一个shell函数 [英] Execute a shell function with timeout
问题描述
为什么会这样工作
超时10秒echofoo bar#foo bar
但这不会
函数echoFooBar {
echofoo bar
}
echoFooBar#foo bar
timeout 10s echoFooBar#timeout:无法运行命令`echoFooBar':没有这样的文件或目录
以及如何让它工作?
timeout
是一个命令 - 所以它在你的bash shell的子进程中执行。因此,它无法访问当前shell中定义的函数。给出的命令 timeout
被执行为一个超时子进程 - 你的shell的一个grand-child进程。
你可能会感到困惑,因为 echo
同时是一个内置的shell和一个单独的命令。
你可以把你的函数放在它自己的脚本文件中,chmod它是可执行的,然后用 timeout
。
或者fork,在子shell中执行你的函数 - 并且在原始进程中监视进度,如果时间太长,会导致子进程死亡。
Why would this work
timeout 10s echo "foo bar" # foo bar
but this wouldn't
function echoFooBar {
echo "foo bar"
}
echoFooBar # foo bar
timeout 10s echoFooBar # timeout: failed to run command `echoFooBar': No such file or directory
and how can I make it work?
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.
这篇关于用超时执行一个shell函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!