红联Linux门户
Linux帮助

脚本

发布时间:2010-09-27 22:39:57来源:红联作者:gswen
下面是shell脚本 -----------
#!/bin/csh
#
# NAME
# keepitup.csh - Keep demons up and running
#
# SYNOPSIS
# keepitup.csh
#
# DESCRIPTION
# If any of the following processes are down, then start them up
# again. This script can be run every few minutes from a crontab.
#
# AUTHOR
# Ken Stevens <kstevens@globeandmail.ca>
foreach daemon ( \
/opt/GIS/apps/EventDispatcher/scripts/EventDispatcher.pl \
/opt/GIS/apps/CatchFTP/scripts/ProcessFTP.pl \
/opt/GIS/apps/NewsHound/scripts/NewsHound.pl \
)
ps -e | fgrep `echo $daemon:t | cut -c1-8` > /dev/null
if ( $status > 0 ) then
echo Restarting $daemon
date
$daemon &
endif
end

备注:这个脚本的思路,就是在crontab定期运行的时候,检测对应名称的进程是否还存在,如果不存在,就重新启动它
局限:对于那些启动之后,detach当前终端session,最终以另外一个程序名运行的情况(比如,启动脚本是apache22,最终进程名称是httpd),需要额外处理。此外,对于启动两个相同名称、不同配置文件的后台进程情况,也需要额外处理。

有没有可以解释一下这个脚本呢?
文章评论

共有 7 条评论

  1. gswen 于 2010-09-29 20:56:38发表:

    不懂啊,只能比别人勤奋点了

  2. deepwhite 于 2010-09-29 07:56:29发表:

    这么晚了了还在看?真用功,呵呵。

    CSH 和 bash 都是 Shell, 但是还是有一些区别的。比如, CSH 里面会自动将 $status 设置为程序的返回值。

    这里有一个网址,里面有 CSh的教程, http://bima.astro.umd.edu/checker/node22.html, 里面有一句话:
    Scripts should by terminated properly by an exit command, optionally returning an error code (0=no error) to the caller.
    This gives the caller the opportunity to catch faulty behavior. After each command the status shell variable contains
    the exit value ($status) of that command.
    可以看到, $statue 是CSH 自动设置的。

  3. gswen 于 2010-09-28 22:10:01发表:

    ps -e | fgrep `echo $daemon:t | cut -c1-8` > /dev/null
    这个命令的返回值是怎么赋值给$status的?

  4. gswen 于 2010-09-28 22:07:23发表:

    关于命令的返回值,有没有什么资料可以介绍一下呢?

  5. deepwhite 于 2010-09-28 21:36:57发表:

    一条命令,可以通过其返回值判断其执行成功与否。

    例如, ls /root 这个命令,如果是root用户执行,那么一切正常,返回值为0 (可以 echo $? 来看一下)。
    而如果普通用户去执行那个命令,则会出错(权限不够),此时返回值为非0值。而在 bash 中,返回值无无符号数,所以可以简单的通过该值是否大于零来判断执行的结果 ---- 为0,则成功,大于零则为失败。

  6. gswen 于 2010-09-28 20:35:13发表:

    ps -e | fgrep `echo $daemon:t | cut -c1-8` > /dev/null
    用这个命令来察看当前进程中是否包含待检查的 daemon ,
    如果不包含,则该命令的返回值不为0,为一个正数. 这个不是很理解?

  7. deepwhite 于 2010-09-28 08:56:22发表:

    [i=s] 本帖最后由 deepwhite 于 2010-9-28 09:00 编辑 [/i]

    脚本 遍历下面的几个 daemon:[code]
    /opt/GIS/apps/EventDispatcher/scripts/EventDispatcher.pl \
    /opt/GIS/apps/CatchFTP/scripts/ProcessFTP.pl \
    /opt/GIS/apps/NewsHound/scripts/NewsHound.pl [/code]对其中的每个 daemon 执行:[code]ps -e | fgrep `echo $daemon:t | cut -c1-8` > /dev/null[/code]用这个命令来察看当前进程中是否包含待检查的 daemon ,
    如果不包含,则该命令的返回值不为0,为一个正数。(这秒命令由两个管道将三个命令连接起来组成,对于其中的每一个命令的具体用法,可以 man 一下,管道的用法请 google )。

    然后检查该命令执行结果的返回值,如果不为0 ( $status > 0 ),则表明当前系统进程中没有 Daemon, 需要重启这个 daemon:[code]
    echo Restarting $daemon
    date
    $daemon &
    [/code]