为什么pgrep在这个进程监视器中失败?

时间:2013-11-15 22:55:01

标签: bash monitor grep

我有一个监视器shell脚本,可以有效地监视并保持进程运行。但它通常会失败,因为它启动了第二个,第三个或更多个过程实例。我也看到pgrep命令(pgrep -n -f wx_nanoserver)在命令行返回错误的pid ......

这是我的剧本:

#!/bin/bash

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

while [ 1 ]; do 
  # timestamp
  ts=`date +%T`
  NOW=`date +"%Y%m%d-%H%M%S"`

  # echo "$ts: begin checking..."
  check_process "wx_nanoserver"
  [ $? -eq 0 ] && echo "$ts: not running, restarting..." && `php /var/www/wx_nanoserver.php > /var/www/logs/wx_output_$NOW.log 2> /var/www/logs/wx_error_$NOW.log &`
  sleep 5
done

2 个答案:

答案 0 :(得分:2)

尝试:

pgrep -n -f "$1" && return 1 || return 0

如果您使用[],您将尝试检查grep stdout数据,并且您的脚本没有将它与空格或sth进行比较,没有[],将使用grep退出代码。

答案 1 :(得分:0)

关于你的剧本的两个奇怪的事情:

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

通过副作用起作用。 ``` part evaluates to either the pid of the process if found, or nothing if no process is found. The single [notation is a synonym for the测试builtin (or command on earlier systems) which happens to return true if its argument is a nonempty string and false if it is given no argument. So when a pid is found, the test becomes something like [1234] which evaluates to true and []`否则,评估为false。这确实是你想要的,但写起来会更清晰:

  pgrep -n -f "$1" &>/dev/null && return 1 || return 0

另一件事是

 `php /var/www/wx_nanoserver.php > /var/www/logs/wx_output_$NOW.log 2> /var/www/logs/wx_error_$NOW.log &`

你没有明显原因使用命令替换。您要求bash评估命令的输出而不是简单地运行它。由于其输出被重定向,它总是计算为空字符串,因此它没有进一步的效果。副作用是命令在子shell中运行,这是对它进行deamonize的好事。虽然,写作会更清晰:

 ( php /var/www/wx_nanoserver.php > /var/www/logs/wx_output_$NOW.log 2> /var/www/logs/wx_error_$NOW.log & )

不确定实际问题是什么。无论如何似乎都是这样工作。

最后的注释,后面勾选`` notation has been deprecated in favour of the $()`符号。

相关问题