进程守护程序

#!/bin/bash
#=========================================
# Filename : watch.sh
# Filetype : Shell
# Author   : Colben
# Create   : 2015-09-08 01:16:35
#=========================================
  
[ 2 -gt $# ] && echo -e "\tUsage:$0 {start|stop} {cmd}\n" && exit 1

pname=`basename $2`
function stop_pw
{
    ppid=`ps -ef|grep "\`basename $0\` \+start \+[^ ]*\<$pname\>"|awk '{print $2}'`
    [ '' != "$ppid" ] && ps -A -o pid,ppid|grep " $ppid$"|awk '{print $1}'|xargs kill && kill $ppid
    exit $1
}
case $1 in
    start)
        ps -ef|grep "`basename $0` \+start \+[^ ]*\<$pname\>"|grep -v " \+$$ \+"
        [ 0 -eq $? ] && echo "$pname is runing, WATCH can not start ..." && exit 2
        pid=0000
        last_stat=0
        last_time=`date +%s`
        shift
        while :
        do
            if [ ! -f /proc/$pid/stat ]
            then
                trap "stop_pw 4" 2 3 15
                $* > /dev/null 2>/dev/null &
                pid=$!
            else
                let "interval=`date +%s`-$last_time"
                [ 600 -gt $interval ] && sleep 4 && continue
                cur_stat=`cat /proc/$pid/stat|awk 'END{print $15+$16}'`
                [ $cur_stat -ne $last_stat ] && last_stat=$cur_stat || kill $pid && sleep 2
                last_time=`date +%s`
            fi
        done >/dev/null 2>/dev/null &
        ;;
    stop)
        stop_pw 0
        ;;
    *)
        echo -e "\tUsage:$0 {start|stop} {cmd}\n"
        ;;
esac

编程技巧