2012-08-13 74 views
0

我想用超時命令與自己的功能,例如:如何使用超時命令與自己的功能?

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

timeout 5 test 

但調用此腳本時,似乎什麼也不做。在我啓動它後shell會立即返回。

有沒有辦法解決這個問題或可以超時不能用於自己的功能?

+0

什麼是timeout命令?它不是內置的bash。 – 2012-08-13 13:27:42

+0

來自另一個SOF鏈接的更多答案: [用超時執行函數](https://stackoverflow.com/questions/9954794/execute-function-with-timeout) – dkb 2016-02-01 06:56:46

回答

2

timeout似乎不是bash的內置命令,這意味着它無法訪問函數。您必須將函數體移到新的腳本文件中,並將其作爲參數傳遞給timeout

3

timeout需要一個命令,並且不能在shell函數上工作。

不幸的是,你上面的函數與/usr/bin/test可執行文件有衝突,這會造成一些混淆,因爲/usr/bin/test會立即退出。如果重命名功能(說)t,你會看到:

[email protected]:~/$ timeout t 
Try `timeout --help' for more information. 

這不是巨大的幫助,但足以說明這是怎麼回事。

1

只要你在一個單獨的腳本隔離你的函數,你可以這樣來做:

(sleep 1m && killall myfunction.sh) & # we schedule timeout 1 mn here 
myfunction.sh 
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 
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變量。