2014-04-04 60 views
0

我想創建一個運行命令的bash腳本,然後在10分鐘後結束它(本身並不困難)。但是,如果再次調用,我希望它將原始腳本的超時重置爲0並退出。Bash腳本,自動超時

目的是在最近10分鐘內調用腳本時執行命令。我考慮過文件+時間戳,但它不是一個優雅的解決方案。也許信號?

在此先感謝! James

+0

會超時應先執行後永久爲0?或者你想在一段時間後重置爲10分鐘? –

+0

是的,我會建議使用信號來實現這個 – arco444

+0

@VasantaKoli我想重置爲10分鐘的超時再次 – jleck

回答

2

當腳本運行時,將腳本的進程ID保存到文件中,並在腳本運行完成後刪除文件。如果具有PID的文件存在,則可以使用該文件作爲向進程發送信號以重置計數器的條件。

#Set the counter to 0 at start and reset the counter on receiving signal USR1 
i=0 
trap "i=0" USR1 

#If script already running, send signal to the PID and exit 
pid_file=/tmp/myscriptpid 
if [[ -e $pid_file ]] 
then 
    kill -s USR1 $(cat $pid_file) 
    exit 0 
fi 

#Otherwise capture the PID and save to file, clean up on exit 
echo "$$" >$pid_file 
trap 'rm -f "$pid_file"' EXIT 

然後你要在後臺運行命令,並殺死它一旦你完成:

#Run the command in the background 
your_command & 
your_command_pid=$! 

#Increment $i once each second. 
count() { 
    sleep 1 
    ((i++)) 
} 

#Note that $i is reset to 0 if the script receives the USR1 signal. 
while (($i < 600)) 
do 
    count 
done 

#Kill the running command once the counter is up to 600 seconds 
kill "$your_command_pid" 
+0

嗨,對不起,也許我沒有解釋得很好。我希望命令可以像保持被調用的文件一樣運行。如果文件沒有被調用,那就是當我需要它死的時候。儘管代碼可以幫助我在正確的道路上,但是,謝謝:) – jleck

+0

我假設你想運行的命令不會終止並無限期地運行。如果你想在10分鐘內一次又一次地調用相同的命令(除非通過再次運行這個腳本來延長10分鐘的超時時間),那麼你就需要將命令調用放在'while'循環中。 – macaptain

0

檢查下面的腳本和更新jleck

#!/bin/bash 
now=$(date +%s) 
final=$(awk 'END {print}' /var/log/count.log 2> /dev/null) 
when=$(date --date @${final} 2> /dev/null) 

if (($(echo $final | wc -w) > 0)); then 
     t1=$(expr $(expr $now - $final)/60) 
     if (($t1 < 30)); then 
       time=0 
     else 
       time=600 
     fi 
else 
     time=600 
fi 

if (($time > 0)); then 
     your_command & 
     PID=$! 
     sleep $time 
     kill -9 $PID 
     date +%s >> /var/log/count.log 
else 
     echo "Command Was Executed on $when, Kindly Execute after $(expr 30 - $t1) minutes" 
fi 

在此之後的首次執行超時將重置爲0,將再次在10分鐘後30分鐘Diffrence