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