本文最后更新于276 天前,其中的信息可能已经过时,如有错误请发送邮件到zhouxingkang2021@163.com
由来
今天在学习shell脚本后,编写一个控制rsync程序启动、停止、重启操作的脚本,脚本内容如下:
[root@Centos7 init.d]# cat /etc/init.d/kk_rsync
#!/bin/bash
# author:zhouxingkang
if [ "$#" -ne "1" ];then
echo "Usage: $0 {start|stop|restart}"
exit 1
fi
# 当用户选择启动rsync
if [ "$1" = "start" ];then
/usr/bin/rsync --daemon
sleep 2
# 验证端口是否真的启动了
if [ `netstat -tunlp|grep rsync|wc -l` -ge 1 ];then
echo "Rsync is started!"
exit 0
fi
# 当用户选择停止rsync
elif [ "$1" = "stop" ];then
pkill rsync &>/dev/null
sleep 2
if [ `ss -tunlp|grep rsync|wc -l` -eq 0 ];then
echo "Rsync is stopped!"
exit 0
fi
# 当用户选择重启rsync
elif [ "$1" = "restart" ];then
killall rsync
sleep 1
killpro=`netstat -tunlp|grep rsync|wc -l`
/usr/bin/rsync --daemon
sleep 1
startpro=`netstat -tunlp|grep rsync|wc -l`
if [ "$killpro" -eq 0 -a "$startpro" -ge 1 ];then
echo "Rsync is restarted!"
exit 0
fi
# 当用户传入非 start,stop,restart 参数
else
echo "Usage: $0 {start|stop|restart}"
exit 1
fi
这个脚本通过参数{start|stop|restart}来启动、停止、重启rsync程序,执行/etc/init.d/kk_rsync start命令时能正常启动rsync,并返回“Rsync is started!”字样,但是执行/etc/init.d/kk_rsync stop时很奇怪,直接返回了Terminated,并没有返回“Rsync is stopped!”字样,如下:
[root@Centos7 init.d]# /etc/init.d/kk_rsync start
Rsync is started!
[root@Centos7 init.d]# /etc/init.d/kk_rsync stop
Terminated
于是,我仔细排查了一下,终于搞明白了这个问题的缘由。
排查过程
我首先查阅了一下这个Terminated这个返回的含义,代表着shell脚本被突然中断了,我看了下脚本里面有一行命令pkill rsync &>/dev/null,表示杀死有关rsync的这个进程,但就是这个命令,可能会kill掉我的脚本执行进程,因为我执行脚本的命令为/etc/init.d/kk_rsync stop,而这个命令里恰好包含rsync,pkill rsync就直接把正在执行的脚本进程kill掉了,导致后面代码没有执行完,为了验证这一个猜想,我将脚本名称修改成不含rsync,在执行一下果然正常了,如下:
[root@Centos7 init.d]# mv kk_rsync kk_rsyn
[root@Centos7 init.d]# /etc/init.d/kk_rsyn stop
Rsync is stopped!
[root@Centos7 init.d]#
脚本成功执行,并返回:“Rsync is stopped!”。