当前位置: 移动技术网 > 网络运营>服务器>Linux > linux下监视进程 崩溃挂掉后自动重启的shell脚本

linux下监视进程 崩溃挂掉后自动重启的shell脚本

2017年12月12日  | 移动技术网网络运营  | 我要评论
=================================================
本文为khler原作,转载必须确保本文完整并完整保留原作者信息及本文原始链接
author: heyuanhui
e-mail: khler@163.com
qq: 23381103
msn: pragmac@hotmail.com
=================================================

如何保证服务一直运行?如何保证即使服务挂掉了也能自动重启?在写服务程序时经常会碰到这样的问题。在linux系统中,强大的shell就可以很灵活的处理这样的事务。
下面的shell通过一个while-do循环,用ps -ef|grep 检查loader进程是否正在运行,如果没有运行,则启动,这样就保证了崩溃挂掉的进程重新被及时启动。
必须注意两点:
1、ps |grep 一个进程时必须加上其路劲,否则容易grep到错误的结果;
2、必须用 -v 从结果中去除grep命令自身,否则结果非空。
复制代码 代码如下:

#!/bin/sh
#=====================
#yuanhui.he
#khler@163.com
#=====================
while :
do
echo "current dir is " $pwd
stillrunning=$(ps -ef |grep "$pwd/loader" |grep -v "grep")
if [ "$stillrunning" ] ; then
echo "tws service was already started by another way"
echo "kill it and then startup by this shell, other wise this shell will loop out this message annoyingly"
kill -9 $pidof $pwd/loader
else
echo "tws service was not started"
echo "starting service ..."
$pwd/loader
echo "tws service was exited!"
fi
sleep 10
done

如果启动此shell时发现进程已经存在,说明以别的方式启动了进程而不是此shell,那么它会持续提醒找到进程,解决办法是,要么只用此shell启动服务,要么一经发现以其他方式启动的服务即kill掉,上面的语句就是这么干的:
kill -9 $pidof $pwd/loader

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网