19

这是一个 bash 脚本示例,它检查某个正在运行的进程(守护程序或服务)并在没有此类进程运行时执行特定操作(重新加载、发送邮件)。

check_process(){
        # check the args
        if [ "$1" = "" ];
        then
                return 0
        fi

        #PROCESS_NUM => get the process number regarding the given thread name
        PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'
        # for degbuging...
        $PROCESS_NUM
        if [ $PROCESS_NUM -eq 1 ];
        then
                return 1
        else
                return 0
        fi
}

# Check whether the instance of thread exists:
while [ 1 ] ; do
        echo 'begin checking...'
        check_process "python test_demo.py" # the thread name
        CHECK_RET = $?
        if [ $CHECK_RET -eq 0 ]; # none exist
        then
                # do something...
        fi
        sleep 60
done

但是,它不起作用。我收到“错误:垃圾选项”。为ps命令。这些脚本有什么问题?谢谢!

4

3 回答 3

39

PROCESS_NUM你可以用这个单线实现几乎所有的事情:

[ `pgrep $1` ] && return 1 || return 0

如果您正在寻找部分匹配,即程序名为foobar,并且您希望您$1只是foo,您可以将其添加-f switch到 pgrep:

[[ `pgrep -f $1` ]] && return 1 || return 0

将它们放在一起,您的脚本可以像这样重新编写:

#!/bin/bash

check_process() {
  echo "$ts: checking $1"
  [ "$1" = "" ]  && return 0
  [ `pgrep -n $1` ] && return 1 || return 0
}

while [ 1 ]; do 
  # timestamp
  ts=`date +%T`

  echo "$ts: begin checking..."
  check_process "dropbox"
  [ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
  sleep 5
done

运行它看起来像这样:

# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox

# SHELL #2
$ dropbox stop
Dropbox daemon stopped.

# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox

希望这可以帮助!

于 2012-02-14T03:16:38.463 回答
26

如果要执行该命令,您可能应该更改:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

到:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)
于 2011-10-10T05:04:43.017 回答
1
PROCESS="process name shown in ps -ef"
START_OR_STOP=1        # 0 = start | 1 = stop

MAX=30
COUNT=0

until [ $COUNT -gt $MAX ] ; do
        echo -ne "."
        PROCESS_NUM=$(ps -ef | grep "$PROCESS" | grep -v `basename $0` | grep -v "grep" | wc -l)
        if [ $PROCESS_NUM -gt 0 ]; then
            #runs
            RET=1
        else
            #stopped
            RET=0
        fi

        if [ $RET -eq $START_OR_STOP ]; then
            sleep 5 #wait...
        else
            if [ $START_OR_STOP -eq 1 ]; then
                    echo -ne " stopped"
            else
                    echo -ne " started"
            fi
            echo
            exit 0
        fi
        let COUNT=COUNT+1
done

if [ $START_OR_STOP -eq 1 ]; then
    echo -ne " !!$PROCESS failed to stop!! "
else
    echo -ne " !!$PROCESS failed to start!! "
fi
echo
exit 1
于 2014-10-30T14:42:43.607 回答