使用bash shell脚本检查程序是否正在运行?

Cha*_*pps 19 shell ps

这是一个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
Run Code Online (Sandbox Code Playgroud)

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

slm*_*slm 37

PROCESS_NUM使用这种单线程,您几乎可以完成所有任务:

[ `pgrep $1` ] && return 1 || return 0
Run Code Online (Sandbox Code Playgroud)

如果你正在寻找一个部分匹配,即程序被命名为foob​​ar,你希望你$1只是foo,你可以添加-f switch到pgrep:

[[ `pgrep -f $1` ]] && return 1 || return 0
Run Code Online (Sandbox Code Playgroud)

把它们放在一起你的脚本可以像这样重做:

#!/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
Run Code Online (Sandbox Code Playgroud)

运行它看起来像这样:

# 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
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


pax*_*blo 26

如果要执行该命令,则应该更改:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'
Run Code Online (Sandbox Code Playgroud)

至:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)
Run Code Online (Sandbox Code Playgroud)