我正在尝试使用以下代码检查进程是否正在运行:
SERVICE="./yowsup/yowsup-cli"
RESULT=`ps aux | grep $SERVICE`
if [ "${RESULT:-null}" = null ]; then
echo "not running"
else
echo "running"
fi
但它仍然在回应它正在运行,尽管它不是。我意识到grep本身就是结果,这就是问题所在。
如何跳过grep并检查进程?
答案 0 :(得分:7)
使用pgrep
:
if pgrep "$SERVICE" >/dev/null 2>&1 ; then
echo "$SERVICE is running"
fi
或更可靠:
if pgrep -f "/path/to/$SERVICE" >/dev/null 2>&1 ; then
echo "$SERVICE is running"
fi
答案 1 :(得分:5)
对于pgrep
不可用的系统,您可以使用:
service="[.]/yowsup/yowsup-cli"
if ps aux | grep -q "$service"; then
echo "not running"
else
echo "running"
fi
[.]
in会强制grep
不列出自己,因为它不匹配[.]
正则表达式。grep -q
可用于避免命令替换步骤。答案 2 :(得分:3)
问题在于,您调用的grep
有时会发现自己处于ps
列表中,因此只有在您以交互方式检查时才会有效:
$ 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
最简单的方法是使用pidof
。它接受完整路径和可执行文件名称:
service="./yowsup/yowsup-cli" # or service="yowsup-cli"
if pidof "$service" >/dev/null; then
echo "not running"
else
echo "running"
fi
pidof
- pgrep
还有更强大的版本。
但是,如果您从脚本启动程序,则可以将其保存到文件中:
service="./yowsup/yowsup-cli"
pidfile="./yowsup/yowsup-cli.pid"
service &
pid=$!
echo $pid > $pidfile
然后使用pgrep
检查:
if pgrep -F "$pidfile" >/dev/null; then
echo "not running"
else
echo "running"
fi
这是/etc/init.d
启动脚本中的常用技巧。
答案 3 :(得分:1)
我认为pidof是为此做的。
function isrunning()
{
pidof -s "$1" > /dev/null 2>&1
status=$?
if [[ "$status" -eq 0 ]]; then
echo 1
else
echo 0
fi
)
if [[ $(isrunning bash) -eq 1 ]]; then echo "bash is running"; fi
if [[ $(isrunning foo) -eq 1 ]]; then echo "foo is running"; fi
答案 4 :(得分:1)
## bash
## function to check if a process is alive and running:
_isRunning() {
ps -o comm= -C "$1" 2>/dev/null | grep -x "$1" >/dev/null 2>&1
}
## example 1: checking if "gedit" is running
if _isRunning gedit; then
echo "gedit is running"
else
echo "gedit is not running"
fi
## example 2: start lxpanel if it is not there
if ! _isRunning lxpanel; then
lxpanel &
fi
## or
_isRunning lxpanel || (lxpanel &)
注意:pgrep -x lxpanel
或pidof lxpanel
仍然报告lxpanel
正在运行,即使它已失效(僵尸);为了实现活跃且正常运行的流程,我们需要使用ps
和grep
答案 5 :(得分:0)
current_pid="$$" # get current pid
# Looking for current pid. Don't save lines either grep or current_pid
isRunning=$(ps -fea | grep -i $current_pid | grep -v -e grep -e $current_pid)
# Check if this script is running
if [[ -n "$isRunning" ]]; then
echo "This script is already running."
fi
答案 6 :(得分:0)
SERVICE="./yowsup/yowsup-cli"
RESULT=`ps aux | grep $SERVICE|grep -v grep`
if [ "${RESULT:-null}" = null ]; then
echo "not running"
else
echo "running"
fi