status函数
status函数用于获取进程的运行状态,有以下几种状态:
${base} (pid $pid) is running...
${base} dead but pid file exists
${base} status unknown due to insufficient privileges.
${base} dead but subsys locked
${base} is stopped
以下的status函数定义语句。注意,此为CentOS 7上语句,比CentOS 6多了一段systemctl的处理,用于Sysv的status状态向systemd的status状态转换。
status() {
local base pid lock_file= pid_file=
# Test syntax.
if [ "$#" = 0 ] ; then
echo $"Usage: status [-p pidfile] {program}"
return 1
fi
if [ "$1" = "-p" ]; then
pid_file=$2 # 指定pidfile
shift 2
fi
if [ "$1" = "-l" ]; then
lock_file=$2 # 指定lockfile
shift 2
fi
base=${1##*/}
if [ "$_use_systemctl" = "1" ]; then
systemctl status ${0##*/}.service
ret=$?
# LSB daemons that dies abnormally in systemd looks alive in
# systemd's eyes due to RemainAfterExit=yes
# lets adjust the reality a little bit
if systemctl show -p ActiveState ${0##*/}.service | grep -q '=active$' && \
systemctl show -p SubState ${0##*/}.service | grep -q '=exited$' ; then
ret=3
fi
return $ret
fi
# First try "pidof"
__pids_var_run "$1" "$pid_file" # 根据给定的pidfile获取program的pid,并返回pid值
RC=$?
if [ -z "$pid_file" -a -z "$pid" ]; then # pid为空,且没有pidfile时,获取program的pid
pid="$(__pids_pidof "$1")"
fi
if [ -n "$pid" ]; then # pid存在,则返回程序正在运行
echo $"${base} (pid $pid) is running..."
return 0
fi
case "$RC" in
0)
echo $"${base} (pid $pid) is running..."
return 0
;;
1) # program进程已死。pid文件存在,但/proc目录下没有对应的文件。
echo $"${base} dead but pid file exists"
return 1
;;
4) # pid文件不可读,错误
echo $"${base} status unknown due to insufficient privileges."
return 4
;;
esac
if [ -z "${lock_file}" ]; then
lock_file=${base}
fi
# See if /var/lock/subsys/${lock_file} exists
if [ -f /var/lock/subsys/${lock_file} ]; then # 检查/var/lock/subsys下是否有lockfile
echo $"${base} dead but subsys locked" # pid不存在,但锁文件存在时
return 2
fi
echo $"${base} is stopped" # 以上都不满足时,表示程序未运行
return 3
}
函数调用方法:
status [-p pidfile] [-l lockfile] program
由于函数定义原因,如果同时提供”-p”和”-l”选项,”-l”选项必须放在”-p”的后面。
|