【问题标题】:Continually running PHP script using Bash使用 Bash 持续运行 PHP 脚本
【发布时间】:2023-03-07 18:27:01
【问题描述】:

我有一个长时间运行的 PHP 脚本,它存在内存泄漏,导致它中途失败。该脚本使用了第 3 方库,我一直无法找到泄漏源。

我想做的是创建一个持续运行 PHP 脚本的 bash 脚本,一次处理 1000 条记录,直到脚本返回一个退出代码,说明它已完成处理所有记录。我认为这应该可以帮助我解决内存泄漏问题,因为脚本会运行 1000 条记录,然后退出,然后会为另外 1000 条记录启动一个新进程。

我对 Bash 不是很熟悉。这可能吗?如何获取 PHP 脚本的输出?

在伪代码中,我正在考虑以下内容:

do:
  code = exec('.../script.php')
   # PHP script would print 0 if all records are processed or 1 if there is more to do
while (code != 0)

【问题讨论】:

    标签: php bash scripting memory-leaks


    【解决方案1】:

    $?在 bash 中为您提供程序的退出代码

    你可以做一些类似的事情

    while /bin/true; do
      php script.php
      if [ $? != 0 ]; then
         echo "Error!";
         exit 1;
      fi
    done
    

    你甚至可以这样做:

    while php script.php; do
       echo "script returned success"
    done
    

    【讨论】:

    • 第二个例子可以正常工作,不需要使用$?和测试。
    • 你不必使用/bin/true,Bash 有一个true 内置函数。你也不需要使用$?。你的第二个例子是正确的方法。
    • 在 shell 中,程序必须在成功时返回 0。记住这个 for 循环 :)
    【解决方案2】:

    使用简单的until循环自动测试PHP脚本的退出状态。

    #!/bin/sh
    until script.php
    do
       :
    done
    

    冒号只是一个空运算符,因为您实际上并不想在循环中做任何其他事情。 until 同时执行命令 script.php 直到它返回零(也就是 true)。如果脚本返回 0 而不是 1 表示未完成,您可以使用 while 而不是 until

    PHP 脚本的输出将进入标准输出和标准错误,因此您可以使用一些 I/O 重定向来包装 shell 脚本的调用,以将输出存储在一个文件中。例如,如果脚本名为loop.sh,您只需运行:

    ./loop.sh > output.txt
    

    当然,您可以直接在 PHP 脚本中控制输出文件;你只需要记住打开文件进行追加。

    您可能想问一个关于如何调试 PHP 内存泄漏的单独问题 :-)

    【讨论】:

      【解决方案3】:

      你必须使用 bash 吗?你可以用 PHP 做到这一点:

      while (true) {
        $output = exec('php otherscript.php', $out, $ret);
      }
      

      $ret 变量将包含脚本的退出代码。

      【讨论】:

      【解决方案4】:

      你可以写:

      #!/bin/bash 
      
      /usr/bin/php prg.php # run the script.
      while [  $? != 0 ]; do # if ret val is non-zero => err occurred. So rerun.
        /usr/bin/php prg.php
      done
      

      【讨论】:

        【解决方案5】:

        在 PHP 中实现的解决方案改为:

        do {
            $code = 1;
            $output = array();
            $file = realpath(dirname(__FILE__)) . "/script.php";
            exec("/usr/bin/php {$file}", $output, $code);
        
            $error = false;
            foreach ($output as $line) {
                if (stripos($line, 'error') !== false) {
                    $error = true;
                }
                echo $line . "\n";
            }
        } while ($code != 0 && !$error);
        

        【讨论】:

          猜你喜欢
          • 2017-12-09
          • 2017-11-04
          • 2011-07-27
          • 1970-01-01
          • 1970-01-01
          • 2016-10-23
          • 1970-01-01
          • 2015-02-23
          • 2011-02-02
          相关资源
          最近更新 更多