【问题标题】:why does pgrep fail in this process monitor?为什么 pgrep 在此进程监视器中失败?
【发布时间】:2013-11-15 22:55:01
【问题描述】:

我有一个监视 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

【问题讨论】:

  • 完全不用支票怎么样?每当您的命令退出时,它将重新开始。 while true; yourcommand ; done你总是可以把那个循环放到后台。
  • 我已经根据这里的优秀建议更新了 shell 脚本。但它并没有解决问题。几天后,php 脚本仍然会运行许多实例。对此有什么想法吗?在命令行中,您不能启动多个实例,因为它侦听一个端口,并且您会收到该端口上已经有一个侦听器的错误。 ... 可能除了一个以外的所有进程都崩溃了,但仍然是个谜:pgrep 仍然看到一个进程,不应该启动另一个进程。

标签: bash monitor grep


【解决方案1】:

尝试:

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

如果你使用 [ ],你将尝试检查 pgrep 标准输出数据,并且你的脚本没有将其与空格或某事进行比较,没有 [ ],将使用 pgrep 退出代码。

【讨论】:

    【解决方案2】:

    关于你的脚本的两个奇怪的地方:

      [ `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 thetestbuiltin (or command on earlier systems) which happens to returntrueif its argument is a nonempty string andfalseif it is given no argument. So when a pid is found, the test becomes something like[ 1234 ]which evaluates to true and[ ]` 否则为假。这确实是你想要的,但写起来会更干净:

      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 中运行,这是对它进行去恶魔化的好方法。不过,写起来会更干净:

     ( 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$()` 表示法。

    【讨论】:

      猜你喜欢
      • 2013-01-02
      • 1970-01-01
      • 2010-10-09
      • 2014-11-23
      • 2014-01-06
      • 1970-01-01
      • 2022-07-19
      • 1970-01-01
      • 2020-07-27
      相关资源
      最近更新 更多