【问题标题】:how to control other scripts by a main script and pass to them parameters when they are running如何通过主脚本控制其他脚本并在它们运行时向它们传递参数
【发布时间】:2013-07-26 02:48:46
【问题描述】:

我有一个 ma​​in.phptest.php

  1. test.php 应该由 ma​​in.php 执行
  2. 这两个脚本都必须无限运行。
  3. ma​​in.php 必须在一段时间内检查 test.php 是否正在运行,如果它没有运行(以防出现错误)再次执行。
  4. 我也必须有错误日志。
  5. 如果 ma​​in.php 收到 'test stop' 它会将 'close' 发送到 test.php 并且 test.php 必须停止(我不知道执行后如何将我的订单(例如'test stop')发送到ma​​in.php?)

我有这个样本:

ma​​in.php

     <?php

function execute(){
    $desc = array(
        0 => array('pipe', 'r'), 
        1 => array('pipe', 'w'),
        2 => array('file', 'log.txt', 'a') 
    );
    $cmd = "start /b C:\wamp\bin\php\php5.4.3\php.exe test.php";
    $p = proc_open($cmd, $desc, $pipes);
    $res[0] = $p;
    $res[1] = $pipes;
    return $res;
}
$res = execute();

while(1) {

    $status = proc_get_status($res[0]);
    if (!$status['running']) {
        $res = execute();
    }

    if ( trim(fgets(STDIN)) == 'stop test' ) {
      fwrite($res[1][0], 'close');

      fclose($res[1][0]);
      fclose($res[1][1]);
      fclose($res[1][2]);
      proc_close($res[0]);
      break;
    }

}
?>

test.php

<?php

while (1) {

     // ---------
     // other commands
     // ---------
     // ---------


$status = trim(fgets(STDIN));

if ($status == 'close') exit();

}
?>

好的,这是我的代码摘要,但它们不能正常工作。

例如,当脚本到达 test.php 中的这一行 $status = trim(fgets(STDIN)); 时,它会等到输入,如果我们不发送任何输入,脚本会停止并且不运行其余代码,但我希望脚本在循环中运行并执行命令,直到 ma​​in.php 将输入传递给他。

我在 Windows 上工作。

【问题讨论】:

  • 为什么连一个简单的答案都没有人回答我??!! :((
  • 如果您的解决方案是针对 linux 的,那没问题。在这里说。我可以将它转换为 Windows 语法。请帮助我:))
  • 明天我开始bounty

标签: php command-line stdin proc-open


【解决方案1】:

我会说 PHP 不是您想要完成的任务的最佳工具。为什么不用 C 或 Visual Basic 之类的语言编写程序?

但它也可以在 PHP 中解决: 我建议创建自己的错误处理函数并通过 set_error_handler('my_custom_error_function') 函数在 test.php 中分配它。

在 my_custom_error_function() 中,您可以记录错误并重新启动 test.php 可以通过 file_put_contents('.\error.log', $error_string, FILE_APPEND)

向日志文件添加一行

fgets() 需要一个打开的文件句柄。因此,您可能需要检查您的例程(或提供更多代码)。您可能还想查看 file_get_contents()。

【讨论】:

    猜你喜欢
    • 2020-07-02
    • 1970-01-01
    • 2021-10-31
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    相关资源
    最近更新 更多