Check if a process is running using Bash

后端 未结 7 943
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 18:53

I am trying to check if a process is running with the code below:

SERVICE=\"./yowsup/yowsup-cli\"
RESULT=`ps aux | grep $SERVICE`

if [ \"${RESULT:-null}\" =         


        
7条回答
  •  情深已故
    2020-12-19 19:34

    The problem is that grep you call sometimes finds himself in a ps list, so it is good only when you check it interactively:

    $ ps -ef | grep bash
    ...
    myaut    19193  2332  0 17:28 pts/11   00:00:00 /bin/bash
    myaut    19853 15963  0 19:10 pts/6    00:00:00 grep --color=auto bash
    

    Easiest way to get it is to use pidof. It accepts both full path and executable name:

    service="./yowsup/yowsup-cli" # or service="yowsup-cli"
    if pidof "$service" >/dev/null; then
        echo "not running"
    else
        echo "running"
    fi
    

    There is more powerful version of pidof -- pgrep.


    However, if you start your program from a script, you may save it's PID to a file:

    service="./yowsup/yowsup-cli"
    pidfile="./yowsup/yowsup-cli.pid"
    service &
    pid=$!
    echo $pid > $pidfile
    

    And then check it with pgrep:

    if pgrep -F "$pidfile" >/dev/null; then
        echo "not running"
    else
        echo "running"
    fi
    

    This is common technique in /etc/init.d start scripts.

提交回复
热议问题