原理说明:使用shell脚本获取项目线程是否正在运行,然后根据指令进行停止/启动/重启/编译运行go项目操作。并且可以结合定时任务进行项目的守护运行。
1.判断当前项目是否运行
pid=`ps -ef | grep "$1" | grep -v 'grep' | grep -v "$0" | awk '{print $2}'`
if [[ $pid != "" ]]
then
echo "$1" "running"
else
echo "$1" "Not Running"
fi
$1为运行脚本时后面跟的参数
2.启动项目
nohup ./"${Name}" >/dev/null 2>&1 &
3.停止项目
kill "${pid}"
4.编译golang项目
go build -o "${Name}"
5.根据上述脚本进行代码的封装。代码如下:
#!/bin/sh
# 假如需要查找go脚本kAdmin是否运行 当前脚本名称为Status.sh 运行:sh Status.sh 'kAdmin'
# 如果需要操作 则第二个参数为:start | restart | stop | build
#项目根目录
cd ..
ShellPath=$(pwd)
Name=$1
startTask(){
# shellcheck disable=SC2164
cd "${ShellPath}"
nohup ./"${Name}" >/dev/null 2>&1 &
echo "starting..."
}
goBuild(){
# shellcheck disable=SC2164
cd "${ShellPath}"
echo "go build begin!"
go build -o "${Name}"
echo "go build Success!"
}
# shellcheck disable=SC2039
if [[ $1 == "" ]]
then
echo "参数错误!如 start.sh kadmin restart"
exit
fi
#查找进程id
# shellcheck disable=SC2006
# shellcheck disable=SC2009
pid=`ps -ef | grep "$1" | grep -v 'grep' | grep -v "$0" | awk '{print $2}'`
# shellcheck disable=SC2039
if [[ $2 == "start" ]]
then
if [[ $pid != "" ]]
then
echo "$1" "is running"
else
startTask
echo "$1" "Start Success..."
fi
elif [[ $2 == "stop" ]]
then
if [[ $pid != "" ]]
then
kill "${pid}"
echo "$1" "Stop Success..."
else
echo "$1" "is Stop"
fi
elif [[ $2 == "restart" ]]
then
if [[ $pid != "" ]]
then
kill "${pid}"
fi
startTask
echo "$1" "Restart Success..."
elif [[ $2 == "build" ]]
then
goBuild
if [[ $pid != "" ]]
then
kill "${pid}"
fi
startTask
else
if [[ $pid == "" ]]
then
echo "$1" "Check Res: Not Running"
startTask
echo "$1" "restart Success!"
else
echo "$1" "Check Res: Running"
fi
fi
6 使用:
#守护运行 若项目停止运行则自动重新启动项目 建议配合cron定时调用此脚本
sh kadmin.sh kadmin
#编译项目
sh kadmin.sh kadmin build
#启动项目
sh kadmin.sh kadmin start
#停止项目
sh kadmin.sh kadmin stop
#重启项目
sh kadmin.sh kadmin restart
注意:
脚本位置必须为项目根目录下一级目录 如: kadmin/shell/kadmin.sh