如何使用自己的函数超时命令?

时间:2012-08-13 13:22:56

标签: bash function shell timeout

我想将timeout命令与自己的函数一起使用,例如:

#!/bin/bash
function test { sleep 10; echo "done" }

timeout 5 test

但是在调用这个脚本时,似乎什么也没做。 shell启动后就会返回。

有没有办法解决这个问题,或者超时不能用于自己的功能?

5 个答案:

答案 0 :(得分:3)

timeout需要一个命令,无法处理shell函数。

不幸的是,上面的函数与/usr/bin/test可执行文件存在名称冲突,这会引起一些混淆,因为/usr/bin/test会立即退出。如果您将功能重命名为(例如)t,您会看到:

brian@machine:~/$ timeout t
Try `timeout --help' for more information.

这不是很有帮助,但可以用来说明正在发生的事情。

答案 1 :(得分:3)

一种方法是做

timeout 5 bash -c 'sleep 10; echo "done"'

代替。虽然你也可以hack up something这样:

f() { sleep 10; echo done; }
f & pid=$!
{ sleep 5; kill $pid; } &
wait $pid

答案 2 :(得分:2)

timeout似乎不是bash的内置命令,这意味着它无法访问函数。您必须将函数体移动到新的脚本文件中,并将其作为参数传递给timeout

答案 3 :(得分:1)

如果您将功能隔离在单独的脚本中,则可以这样做:

(sleep 1m && killall myfunction.sh) & # we schedule timeout 1 mn here
myfunction.sh

答案 4 :(得分:1)

在尝试自己实现这个问题时发现了这个问题,并且根据@ 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变量。

相关问题