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

发布时间:2020-04-17编辑:脚本学堂
在linux系统中,使用shell来监测进程的运行状态,发现挂掉后,即自动重启,从而保障了服务的持续运行。有需要的朋友,参考下吧。

本文介绍的这个shell/ target=_blank class=infotextkey>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 从结果中去除linuxjishu/14086.html target=_blank class=infotextkey>grep命令自身,否则结果非空。

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