在运行超过指定时间的bash中杀死进程?

时间:2009-10-04 13:52:18

标签: bash

我在/etc/init.d目录中有Oracle的关闭脚本 它在“停止”命令中执行:

su oracle -c "lsnrctl stop >/dev/null"
su oracle -c "sqlplus sys/passwd as sysdba @/usr/local/PLATEX/scripts/orastop.sql >/dev/null"

.. 问题是当lsnrctl或sqlplus没有响应时 - 在这种情况下,这个“停止”脚本永远不会结束,服务器无法关闭。唯一的方法 - 就是“杀死 - 9”那个。

我想重写脚本,以便在5分钟后(例如)如果命令没有完成 - 它应该被终止。

我怎么能做到这一点?你能举个例子吗? 我在Linux RHEL 5.1 + bash。

2 个答案:

答案 0 :(得分:9)

如果能够使用第三方工具,我会利用您可以从脚本中调用的第三方预先编写的帮助程序(doalarmtimeout都被{ {3}})。

如果不使用这些工具自己写这样的东西,我可能会做类似以下的事情:

function try_proper_shutdown() {
  su oracle -c "lsnrctl stop >/dev/null"
  su oracle -c "sqlplus sys/passwd as sysdba @/usr/local/PLATEX/scripts/orastop.sql >/dev/null"
}

function resort_to_harsh_shutdown() {
  for progname in ora_this ora_that ; do
    killall -9 $progname
  done
  # also need to do a bunch of cleanup with ipcs/ipcrm here
}

# here's where we start the proper shutdown approach in the background
try_proper_shutdown &
child_pid=$!

# rather than keeping a counter, we check against the actual clock each cycle
# this prevents the script from running too long if it gets delayed somewhere
# other than sleep (or if the sleep commands don't actually sleep only the
# requested time -- they don't guarantee that they will).
end_time=$(( $(date '+%s') + (60 * 5) ))
while (( $(date '+%s') < end_time )); do
  if kill -0 $child_pid 2>/dev/null; then
    exit 0
  fi
  sleep 1
done

# okay, we timed out; stop the background process that's trying to shut down nicely
# (note that alone, this won't necessarily kill its children, just the subshell we
# forked off) and then make things happen.    
kill $child_pid
resort_to_harsh_shutdown

答案 1 :(得分:6)

哇,这是一个复杂的解决方案。这里更简单。您可以跟踪PID并在以后将其终止。

my command & #where my command is the command you want to run and the & sign backgrounds it.
PID=$! #PID = last run command.
sleep 120 && doProperShutdown || kill $PID #sleep for 120 seconds and kill the process properly, if that fails, then kill it manually..  this can be backgrounded too.