代码之家  ›  专栏  ›  技术社区  ›  Matt McCormick

使用Bash连续运行PHP脚本

  •  0
  • Matt McCormick  · 技术社区  · 15 年前

    我想做的是创建一个bash脚本,它连续运行PHP脚本,一次处理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)
    
    5 回复  |  直到 15 年前
        1
  •  1
  •   Robin    15 年前

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

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

        2
  •  3
  •   naumcho    15 年前

    $? 提供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
    
        3
  •  1
  •   Emil Sit    15 年前

    使用简单的 until

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

    直到 执行命令时 script.php while 而不是 .

    loop.sh ,您只需运行:

    ./loop.sh > output.txt
    

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

        4
  •  1
  •   codaddict    15 年前

    你可以写:

    #!/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
  •  0
  •   Matt McCormick    15 年前

    在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);
    
    推荐文章