2014-09-19 53 views
1

我想重複運行程序最多5秒鐘。如何在一段時間內繼續運行程序?

我知道timeout指定的時間量,例如,執行命令:

timeout 5 ./a.out 

但我要繼續執行程序,直到5秒過去了,所以我可以告訴它如何 多次獲得執行。

我想,我需要這樣的:

timeout 5 `while true; do ./a.out; done` 

,但是這是行不通的。我已經嘗試創建一個shell腳本,用於計算每個循環迭代耗用的時間,並從開始時間 中減去它,但效率不高。

任何幫助,將不勝感激。

+2

你嘗試'超時5的bash -c「,而真實;做./a。 out; done「' – 2014-09-19 06:39:35

+0

如果你想使用'timeout',命令是'timeout 5s。/ a.out' – 2014-09-19 07:35:05

+0

是的,我發現bash -c」「會這麼做!謝謝你的提示 :) – 2014-09-19 14:48:16

回答

0

如果你想使用的超時:

timeout 5s ./a.out 

您可以編寫一個簡短的腳本,輕鬆地設置與date -d "date string" +%send time獲得以秒爲將來的時間。然後,只需比較current timeend time並打破true。這允許您在執行期間捕獲更多數據。例如,以下代碼將來會設置結束時間5 seconds,然後循環直到current time等於end

#!/bin/bash 

end=$(date -d "+ 5 seconds" +%s)  # set end time with "+ 5 seconds" 
declare -i count=0 

while [ $(date +%s) -lt $end ]; do  # compare current time to end until true 
    ((count++)) 
    printf "working... %s\n" "$count" # do stuff 
    sleep .5 
done 

輸出:

$ bash timeexec.sh 
working... 1 
working... 2 
working... 3 
working... 4 
working... 5 
working... 6 
working... 7 
working... 8 
working... 9 

在你的情況,你會做這樣的事情

./a.out &        # start your application in background 
apid=$(pidof a.out)      # save PID of a.out 

while [ $(date +%s) -lt $end ]; do 
    # do stuff, count, etc. 
    sleep .5       # something to prevent continual looping 
done 

kill $apid        # kill process after time test true 
相關問題