我有一个非常好的bash for循环任务。但情况是,一些迭代似乎没有终止。我正在寻找的是一种引入超时的方法,如果command
的迭代在例如for somecondition; do
while time-run(command) < 2h do
continue command
done
done
之后没有终止两个小时它将终止,然后继续下一次迭代。
粗略轮廓:
{{1}}
答案 0 :(得分:2)
一种(繁琐)方式是在后台启动进程,然后启动另一个后台进程,尝试在固定超时后终止第一个进程。
timeout=7200 # two hours, in seconds
for somecondition; do
command & command_pid=$!
( sleep $timeout & wait; kill $command_pid 2>/dev/null) & sleep_pid=$!
wait $command_pid
kill $sleep_pid 2>/dev/null # If command completes prior to the timeout
done
wait
命令阻塞,直到原始命令完成,无论是自然还是因为它在sleep
完成后被杀死。如果用户试图中断该过程,则会wait
之后立即使用sleep
,因为sleep
会忽略大多数信号,但wait
是可中断的。
答案 1 :(得分:0)
如果我正确理解你的要求,你就有一个需要运行的过程,但你想确保如果它被卡住了就继续,对吗?我不知道这是否会完全帮助你,但这是我写了一段时间回来做类似的事情(我已经改进了一点,但我现在只能获得一个要点,我会稍后用更好的版本更新)。
#!/斌/庆典
######################################################
# Program: logGen.sh
# Date Created: 22 Aug 2012
# Description: parses logs in real time into daily error files
# Date Updated: N/A
# Developer: @DarrellFX
######################################################
#Prefix for pid file
pidPrefix="logGen"
#output direcory
outDir="/opt/Redacted/logs/allerrors"
#Simple function to see if running on primary
checkPrime ()
{
if /sbin/ifconfig eth0:0|/bin/grep -wq inet;then isPrime=1;else isPrime=0;fi
}
#function to kill previous instances of this script
killScript ()
{
/usr/bin/find /var/run -name "${pidPrefix}.*.pid" |while read pidFile;do
if [[ "${pidFile}" != "/var/run/${pidPrefix}.${$}.pid" ]];then
/bin/kill -- -$(/bin/cat ${pidFile})
/bin/rm ${pidFile}
fi
done
}
#Check to see if primary
#If so, kill any previous instance and start log parsing
#If not, just kill leftover running processes
checkPrime
if [[ "${isPrime}" -eq 1 ]];then
echo "$$" > /var/run/${pidPrefix}.$$.pid
killScript
commands && commands && commands #Where the actual command to run goes.
else
killScript
exit 0
fi
然后我将此脚本设置为每小时在cron上运行。每次运行脚本时,它都是
如果这不能让你平方让我知道。
一些注意事项: