在bash for循环中引入超时

时间:2013-09-22 19:56:46

标签: bash shell for-loop scripting timeout

我有一个非常好的bash for循环任务。但情况是,一些迭代似乎没有终止。我正在寻找的是一种引入超时的方法,如果command的迭代在例如for somecondition; do while time-run(command) < 2h do continue command done done 之后没有终止两个小时它将终止,然后继续下一次迭代。

粗略轮廓:

{{1}}

2 个答案:

答案 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上运行。每次运行脚本时,它都是

  • 创建一个以一个变量命名的锁文件,该变量描述包含该脚本实例的pid的脚本
  • 调用killScript函数:
    • 使用find命令查找该脚本版本的所有锁定文件(这样可以将这些脚本中的多个设置为同时在cron中运行,用于不同的任务)。对于它找到的每个文件,它会终止该锁定文件的进程并删除锁定文件(它会自动检查它是否自杀)
  • 开始做我需要运行的任何事情,而不是被卡住(我已经省略了,因为它是我在python中重做的可怕的bash字符串操作)。

如果这不能让你平方让我知道。


一些注意事项:

  • checkPrime函数做得不好,应该返回状态,或者只是退出脚本本身
  • better个方法来创建锁定文件并保证安全,但到目前为止这对我有用(着名的遗言)