linux系统下实现java包开机自启动,即使java进程被异常关闭,也会自启动。
一、app_start.sh
程序启动文件
- 1.复制以下内容,另存为
app_start.sh
,将文件上传至linux服务器。
#!/bin/sh
CurPath=$(cd "$(dirname "$0")"; pwd)
cd ${CurPath}
pid=`ps -ef | grep zhyb_monitor | grep -v grep | awk -F ' ' '{print $2}'`
if [ "$pid" != "" ];then
ps -ef | grep zhyb_monitor | grep -v grep | awk -F ' ' '{print $2}'|xargs kill -9
fi
pid=`ps -ef | grep zhyb.jar | grep -v grep | awk -F ' ' '{print $2}'`
if [ "$pid" != "" ];then
ps -ef | grep zhyb.jar | grep -v grep | awk -F ' ' '{print $2}'|xargs kill -9
fi
chmod a+x zhyb_monitor.sh
echo week:`date +"%w %Y/%m/%d, %H:%M:%S"` 'start zhyb '
./zhyb_monitor.sh &> /dev/null &
echo week:`date +"%w %Y/%m/%d, %H:%M:%S"` 'start zhyb succeed'
cd -
- 2.将
app_start.sh
文件权限设置为可执行权限,将文件添加至/etc/rc.local
内容中,实现开机自启动。
设置可执行权限
chmod +x app_start.sh
/etc/rc.local文件,实现开机自启动
cd /hone/appdir/
(./app_start.sh &)
cd--
二、app_monitor.sh
程序自启动文件
- 防止程序异常停止,自动重启jar包,**需要配合app_start.sh文件使用
#! /bin/sh
#进程名字可修改
source /etc/profile
PRO_NAME=zhyb.jar
mkdir -p nohupLog/`date +%Y-%m`
LOG_PATH=./nohupLog/`date +%Y-%m`/log-`date +%Y-%m-%d`.txt
#定义启动eiota_server程序的函数,&运行在后台
start_server(){
nohup java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8175 -jar ./zhyb.jar >> ${LOG_PATH} 2>&1 &
}
while true ; do
#用ps获取$PRO_NAME进程数量
NUM=`ps aux | grep -w ${PRO_NAME} | grep -v grep |wc -l`
echo "${PRO_NAME} running num is ${NUM} "
#echo $NUM
#少于1,重启进程
if [ "${NUM}" -lt "1" ];then
echo "${PRO_NAME} was killed"
start_server
#大于1,杀掉所有进程,重启
elif [ "${NUM}" -gt "1" ];then
echo "more than 1 ${PRO_NAME},killall ${PRO_NAME}"
ps -ef | grep ${PRO_NAME} | grep -v grep | awk -F ' ' '{print $2}'|xargs kill -9
start_server
fi
#kill僵尸进程
NUM_STAT=`ps aux | grep -w ${PRO_NAME} | grep T | grep -v grep | wc -l`
if [ "${NUM_STAT}" -gt "0" ];then
ps -ef | grep ${PRO_NAME} | grep -v grep | awk -F ' ' '{print $2}'|xargs kill -9
start_server
fi
sleep 5s
done
exit 0