PHP用fgets()读取子脚本输出

时间:2017-03-02 20:58:17

标签: php

我正在运行ScriptA和ScriptB,A在完成每个功能后执行B. B echos个消息。事情是:B的功能可能会卡住,因为他们向短会话到期的慢速服务器请求数据,所以我试图在自上次回显消息后经过一定时间后杀死B.这是一个例子:
ScriptB:

echo "string1\n";  
sleep(1);  
echo "string2\n";  
sleep(1);  
echo "string3\n";  
sleep(1);  
echo "string4\n";  
sleep(3);  
echo "string5\n";

ScriptA

$cmd = "php ScriptB";
$timeout_tolerance = 2; // 
$last_response = time(); // start time

ob_implicit_flush(true);
ob_end_flush();

$descriptorspec = array(
   0 => array("pipe", "r"),   // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),   // stdout is a pipe that the child will write to
   2 => array("pipe", "w")    // stderr is a pipe that the child will write to
);
flush();
$process = proc_open($cmd, $descriptorspec, $pipes, null, array());
echo "here is 1\n";
if (is_resource($process)) {
    while ($s = fgets($pipes[1])) {
        print $s;
        $m = $s;
        $last_response = time();
        while ($s === $m) {
            echo "here is 2\n";
            $m = fgets($pipes[1]);
            if((time() - $last_response) > $timeout_tolerance){
                echo "here is 3\n";
                break;
            }
            echo "here is 4\n";
            sleep(2);
        }
    }
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);
    echo "here is 5\n";
}

当我运行脚本A时,这就是我得到的输出:

here is 1
string1
here is 2
here is 4
string3
here is 2
here is 4
string5
here is 2
here is 4
here is 5

你可能会看到;输出string2string4并且在回显string5之前应该杀死scriptB。我知道这是我的代码上的错误,事情是我从未使用fgets()这样的函数,而我很难理解它们。

0 个答案:

没有答案