如何通过主脚本控制其他脚本,并在它们运行时将参数传递给它们


how to control other scripts by a main script and pass to them parameters when they are running

我有一个main.phptest.php.

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

我有这个样品:

main.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));行时,它会等待输入,如果我们不为其发送任何输入,脚本会停止并不运行其余代码,但我希望脚本在循环中运行并执行命令,直到main.php将输入传递给他。

我正在修窗户。

我想说,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()。