当前位置: > shell编程 >

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

时间:2014-09-30 20:35来源:linux.it.net.cn 作者:it
在linux系统中,使用shell来监测进程的运行状态,发现挂掉后,即自动重启,从而保障了服务的持续运行。

本文介绍的这个shell脚本,通过一个while-do循环,用ps -ef|grep 检查loader进程是否正在运行,如果没有运行,则启动,确保崩溃挂掉的进程,及时自动重启。

脚本内容如下:
 

复制代码代码示例:
#!/bin/sh
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

注意:
1、ps |grep 一个进程时必须加上路径,否则grep时会有不明错误;
2、必须用 -v 从结果中去除grep命令自身,否则结果非空。

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

(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容