如何在Linux下管理Java进程
如何在Linux下管理Java进程
本篇介绍一下如何在Linux下管理java进程。由于在Linux下ps命令的强大,在linux下并不需要像Windows系统那样费力的区分不同的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
#!/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
#!/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
crontab -e
Shell代码
- 0-59 * * * * * /....path of crntb.sh.../crntb.sh
0-59 * * * * * /....path of crntb.sh.../crntb.sh
这样就可以每分钟查看当前pid对应的进程是不是还在,如果不在了,就重新启动。
当然,光用这几小段代码是不足以维护一个完整的商用程序的。但是,做到了这点,最起码万里长征的第一步已经迈出去了。
评论暂时关闭