如何在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代码
  1. #!/bin/sh   
  2. #   
  3. # start/stop the Service   
  4.   
  5. #   
  6. # do some init here   
  7. #   
  8. case "$1" in   
  9. 'restart')   
  10.        
  11.     # first Stopping the Service   
  12.     PID=`sed -n 1p pidfile`  #get pid from file   
  13.     if [ ! -z "$PID" ] ; then   
  14.                 echo "Stopping the Service, begin killing ${PID}"  
  15.          kill ${PID} >/dev/null 2>&1  
  16.          sleep 2  
  17.     fi   
  18.     # second Starting the Service   
  19.     if [ some condition here ]; then    
  20.          echo "Starting the Service"  
  21.          java -classpath some_class_path_here -jar helloworld.jar &    
  22.          echo $! > pidfile   #record process id to file   
  23.     fi   
  24.     ;;   
  25. 'stop')   
  26.     # Stopping the Service   
  27.     PID=`sed -n 1p pidfile`  #get pid from pidfile   
  28.     if [ ! -z "$PID" ] ; then   
  29.             echo "Stopping the Service, begin killing ${PID}"  
  30.          kill ${PID} >/dev/null 2>&1  
  31.     fi   
  32.     ;;   
  33. *)   
  34.     echo "Unmarkable usage: $0 {restart|stop}"  
  35.     ;;   
  36. esac   

 然后再做一个crontab需要执行的脚本:crntb.sh

Shell代码
  1. #!/bin/sh   
  2. PID=`sed -n 1p pidfile`   
  3. cmd=`ps -e|grep $PID`    #get process with the given pid   
  4. indx=`expr index "$cmd" "java"`   #whether the string 'cmd' contains 'java'  
  5.   
  6. if [ "$indx" = "0" ]; then   
  7.   /...path of ctrl.sh.../ctrl.sh restart   
  8. fi  

 最后在crontab中每分钟执行上面的crntb.sh

Shell代码
  1. crontab -e  

 

Shell代码
  1. 0-59 * * * * * /....path of crntb.sh.../crntb.sh  

 这样就可以每分钟查看当前pid对应的进程是不是还在,如果不在了,就重新启动。 

当然,光用这几小段代码是不足以维护一个完整的商用程序的。但是,做到了这点,最起码万里长征的第一步已经迈出去了。

相关内容