杀戮过程由bash脚本启动,但不是脚本本身

时间:2016-08-30 15:12:08

标签: linux bash

所以基本上我有一个脚本让服务器保持活着状态。它启动服务器进程,然后在进程停止后再次启动它。虽然有时服务器变得没有响应。为此我想要另一个脚本来ping服务器,如果它在60秒内没有响应就会终止进程。

问题是,如果我终止服务器进程,bash脚本也会被终止。

启动脚本只是while do: sh Server.sh。它调用其他shell脚本,该脚本具有用于启动服务器的其他参数。服务器正在使用java,因此它启动了一个java进程。如果服务器挂起,我使用kill -9 pid因为没有别的东西阻止它。如果服务器没有挂起并且通常重新启动它会正常停止并且bash脚本开始第二次循环。

1 个答案:

答案 0 :(得分:3)

做正确的事

使用真正的流程监管系统 - 您的Linux发行版几乎肯定包括一个。

通过PID直接监控受监督的流程

一个糟糕的,丑陋的,适度的错误方法(例如,在发生PID碰撞时能够杀死错误的进程)如下:

while :; do
  ./Server.sh & server_pid=$!
  echo "$server_pid" > server.pid
  wait "$server_pid"
done

......并且,要杀死这个过程:

#!/bin/bash
#      ^^^^ - DO NOT run this with "sh scriptname"; it must be "bash scriptname".

server_pid="$(<server.pid)"; [[ $server_pid ]] || exit
# allow 5 seconds for clean shutdown -- adjust to taste
for (( i=0; i<5; i++ )); do
  if kill -0 "$server_pid"; then
    sleep 1
  else
    exit 0 # server exited gracefully, nothing else to do
  fi
done

# escalate to a SIGKILL
kill -9 "$server_pid"

请注意,我们将服务器的PID存储在我们的pid文件中,并将其直接删除 - 从而避免无意中将监控脚本作为目标。

通过lockfile

监控受监督的进程和所有子进程

请注意,这是使用某些特定于Linux的工具 - 但您 在您的问题上有

更强大的方法 - 即使在pidfile重用的情况下也能在重新启动时工作 - 是使用锁文件:

while :; do
  flock -x Server.lock sh Server.sh
done

......而在另一端:

#!/bin/bash

# kill all programs having a handle on Server.lock
fuser -k Server.lock
for ((i=0; i<5; i++)); do
  if fuser -s Server.lock; then
    sleep 1
  else
    exit 0
  fi
done
fuser -k -KILL Server.lock