我想用超时命令与自己的功能,例如:如何使用超时命令与自己的功能?
#!/bin/bash
function test { sleep 10; echo "done" }
timeout 5 test
但调用此脚本时,似乎什么也不做。在我启动它后shell会立即返回。
有没有办法解决这个问题或可以超时不能用于自己的功能?
我想用超时命令与自己的功能,例如:如何使用超时命令与自己的功能?
#!/bin/bash
function test { sleep 10; echo "done" }
timeout 5 test
但调用此脚本时,似乎什么也不做。在我启动它后shell会立即返回。
有没有办法解决这个问题或可以超时不能用于自己的功能?
timeout
似乎不是bash
的内置命令,这意味着它无法访问函数。您必须将函数体移到新的脚本文件中,并将其作为参数传递给timeout
。
timeout
需要一个命令,并且不能在shell函数上工作。
不幸的是,你上面的函数与/usr/bin/test
可执行文件有冲突,这会造成一些混淆,因为/usr/bin/test
会立即退出。如果重命名功能(说)t
,你会看到:
[email protected]:~/$ timeout t
Try `timeout --help' for more information.
这不是巨大的帮助,但足以说明这是怎么回事。
只要你在一个单独的脚本隔离你的函数,你可以这样来做:
(sleep 1m && killall myfunction.sh) & # we schedule timeout 1 mn here
myfunction.sh
一种方式是做
timeout 5 bash -c 'sleep 10; echo "done"'
代替。虽然你也可以hack up something这样的:
f() { sleep 10; echo done; }
f & pid=$!
{ sleep 5; kill $pid; } &
wait $pid
发现当试图此实现自己,从@ geirha的回答工作这个问题,我得到了以下工作:
#!/usr/bin/env bash
# "thisfile" contains full path to this script
thisfile=$(readlink -ne "${BASH_SOURCE[0]}")
# the function to timeout
func1()
{
echo "this is func1";
sleep 60
}
### MAIN ###
# only execute 'main' if this file is not being source
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
#timeout func1 after 2 sec, even though it will sleep for 60 sec
timeout 2 bash -c "source $thisfile && func1"
fi
由于timeout
执行命令它在一个新的shell中给出,诀窍是让子shell环境获取脚本来继承你想运行的函数。第二个诀窍是让它有点可读......,这导致了thisfile
变量。
什么是timeout命令?它不是内置的bash。 – 2012-08-13 13:27:42
来自另一个SOF链接的更多答案: [用超时执行函数](https://stackoverflow.com/questions/9954794/execute-function-with-timeout) – dkb 2016-02-01 06:56:46