linux如何正常关闭java服务,不用kill -9

linux如何正常关闭java服务,不用kill -9,第1张

正常的java程序,你启动,ctrl+c退出的时候也跟着退出了。

用nohup /run.sh & 这样的需要用kill -9 或者你自己写一个特殊的sh用来专门杀这个进程也可以、

您好,方法首先登录linux服务器。方式1:输入【pgrep 进程名称】即可获取到pid列表。方式2:使用【ps】命令查看进程pid。例如:ps -ef|grep java -e:显示所有进程。-f :做一个更为完整的输出。| 管道grep xxxx 筛选出xxxx的进程。方式3:使用【top】命令查看进程pid。 在命令行输入:top 按下回车键即可。【ctrl+c】是退出top界面。方式4:通过【ls /proc】命令查看进程pid。Linux在启动一个进程时,系统会在/proc下创建一个以PID命名的文件 夹。每一个数字文件夹就是对应的一个进程pid。查出需要关闭的进程ID后,使用命令【pkill -9 进程ID】即可删除关闭进程。

首先,这段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

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

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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/yw/8324418.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-15
下一篇2023-04-15

发表评论

登录后才能评论

评论列表(0条)

    保存