教学之友,学习之友。

站长教学网

用shell监控脚本进程,如挂掉就重启它

时间:2012-12-04 16:23来源:未知 作者:ken 点击:

一.

一个php脚本,经常跑了好几个小时,然后莫名其妙的挂掉,不胜其烦。在没有找到真正的原因之前,只好先写一个daemon作用的shell script来monitor,在发现脚本挂掉后,重启脚本.

以下是在chinaunix找到的相关内容,汇集了各位大神们的意见:

http://bbs.chinaunix.net/thread-1487627-1-1.html

============================================================

请教如何写一个shell监控我的一个进程状态,死了重启

#/bin/sh
while true; do
                count=`ps -fe |grep "main" | grep -v "grep"`
                if [ "$?" != "0" ]; then
    echo ">>>>no main,run it"
    else
    echo ">>>>main is running"
    fi
    sleep 2
done

---------------------------------分割线----------------------------------------------
按照2楼的方法,我的板子里没有wc,也没有crontab

我在终端上执行这个脚本./test,能正确检测,
但是我执行./test &,不管main有没有,都是输出no main,run it

---------------------------貌似解决了------------------------------------
在done后面加 &

============================================================

 整体思路看来就是:实现查找进程(ps -ef|grep命令),截取进程字符串关键信息判断是否为空(字符串赋值),执行重启命令(为空时)或跳过(不为空时),用crontab或者循环语句实现定时判断。站长教学网 eduyo.com

发现一个哥们儿写的比我好,拿过来给大家借鉴一下。

 #!/bin/bash
CheckProcess()
{
        if [ "$1" = ""];
        then
                return 1
        fi

    PROCESS_NUM=`ps -ef | grep "$1" | grep -v "grep" | wc -l`
    if [ $PROCESS_NUM -eq 1 ];
    then
        return 0
    else
        return 1
    fi   
}

while [ 1 ] ; do
    CheckProcess "./a.out"
    CheckQQ_RET=$?
    if [ $CheckQQ_RET -eq 1 ];
    then
     killall -9 a.out
     exec ./a.out &
    fi
    sleep 1
done

二.

然后, if 的真正模型是:

if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi

其实, bash中的help if就给了你正确的答案, 但我不知道什么原因无数人就是忽略了它, 而非常多的bash教学资料中都采用了本文开头提出的那种模型来告诉你关于if 结构的事.

注意: [ "$1" = "-a" ] 只一个命令, [ 是命令名!, "$1"是第一个参数, =是第二个参数, "-a"是第三个, ]是第4个. 是[这个命令, 而不是bash本身在报怨 [ "$1" = "-a"] 这样的结构造成的错误, 因为[这个命令对它的参数有所期望, 它期望最后一个参数是 ], 而你用"-a"] 这种连写的形式, 它得到的就只有3个参数: $1, = 和 -a].

 

三.

在运行该脚本时,发现如下错误:syntax error near unexpected token `else'

问题解决:

1.使用 sh -x change.sh看看哪个地方的有问题

2.使用 dos2unix 字符转换工具 convert file formating

3.如果还没有解决,那只能手动将内容重写一遍

 

老外这么说:

Solution:
The customer in this case had downloaded the script off our website from a Win95 box,
and then moved the file to the Linux box. This caused DOS ASCII end-of-line characters
to be placed in the script. The solution is to download the script from the Linux box, as
moving it from the Windows environment will always place undesireable characters in
the script.

Or ftp the file in ASCII mode when transfering from Win95 to Linux.

(责任编辑:ken)
TAG标签: shell 脚本 监控
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
注册登录:不允许匿名留言,登录后留言无需输入验证码。
栏目列表
最新内容