Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2245072
  • 博文数量: 310
  • 博客积分: 6853
  • 博客等级: 准将
  • 技术积分: 2833
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-04 16:41
文章分类

全部博文(310)

文章存档

2013年(17)

2012年(42)

2011年(76)

2010年(71)

2009年(99)

2007年(2)

2006年(1)

2005年(2)

分类: LINUX

2011-03-07 13:16:34

http://www.cnblogs.com/khler/archive/2011/01/28/1947016.html

=================================================
本文为khler原作,转载必须确保本文完整并完整保留原作者信息及本文原始链接

Author: HeYuanHui
E-mail: 
QQ:     23381103
MSN:   
=================================================

 

如何保证服务一直运行?如何保证即使服务挂掉了也能自动重启?在写服务程序时经常会碰到这样的问题。在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 -"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

 

阅读(10910) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~