记得以前做过一个简单的ftp数据导入数据库的java程序,就是每天会定时读取ftp的文件夹,如果存在文件就把文件中的数据入库,然后删除该文件。
但是不知道什么原因在读取过程中java进程会莫名其妙的挂掉,然后每次重启后又从头读。
后来就在程序中加了断点记录读取。然后在服务器上做了一个脚本让它监控java进程,如果挂掉就自动启动。时间久了已经忘了具体的,把
记事本里边保存的东西记录下。
但是在Linux下,需要对进程进行这样的管理:一个商用的服务系统,需要提供的是24小时不间断的服务,
但是由于各种原因,有可能会造成当前java进程对应的JVM的crash。
因此,本篇介绍如何写一段shell脚本方便的启动、停止、守护一个java进程。
首先,这段shell应该有start和stop的功能。
如何stop当前我想停止的进程在Linux下有很多方法,我用的方法是,
启动时将进程对应的process id记录到一个文件中,在停止这个进程时,
从文件中读取process id进行kill。同时,做一个crontab,
不停在系统中查找文件中的process id对应的进程是否存在,
如果不存在,重新启动该进程。
启动和停止脚本:ctrl.sh
Shell代码
#!/bin/sh
#
# start/stop the Service
#
# do some init here
#
case "$1" in
'restart')
# first Stopping the Service
PID=`sed -n 1p pidfile` #get pid from file
if [ ! -z "$PID" ] ; then
echo "Stopping the Service, begin killing ${PID}"
kill ${PID} >/dev/null 2>&1
sleep 2
fi
# second Starting the Service
if [ some condition here ]; then
echo "Starting the Service"
java -classpath some_class_path_here -jar helloworld.jar &
echo $! > pidfile #record process id to file
fi
;;
'stop')
# Stopping the Service
PID=`sed -n 1p pidfile` #get pid from pidfile
if [ ! -z "$PID" ] ; then
echo "Stopping the Service, begin killing ${PID}"
kill ${PID} >/dev/null 2>&1
fi
;;
*)
echo "Unmarkable usage: $0 {restart|stop}"
;;
esac
然后再做一个crontab需要执行的脚本:crntb.sh
Shell代码
#!/bin/sh
PID=`sed -n 1p pidfile`
cmd=`ps -e|grep $PID` #get process with the given pid
indx=`expr index "$cmd" "java"` #whether the string 'cmd' contains 'java'
if [ "$indx" = "0" ]; then
/...path of ctrl.sh.../ctrl.sh restart
fi
最后在crontab中每分钟执行上面的crntb.sh
Shell代码
crontab -e
Shell代码
0-59 * * * * * /....path of crntb.sh.../crntb.sh
分 小时 日 月 星期 命令
0-59 0-23 1-31 1-12 0-6 command (取值范围,0表示周日一般一行对应一个任务)
记住几个特殊符号的含义:
“*”代表取值范围内的数字,
“/”代表”每”,
“-”代表从某个数字到某个数字,
“,”分开几个离散的数字
这样就可以每分钟查看当前pid对应的进程是不是还在,如果不在了,就重新启动。
当然,光用这几小段代码是不足以维护一个完整的商用程序的。但是,做到了这点,最起码万里长征的第一步已经迈出去了