2

我需要在 PHP 中捕获子进程的输出来操作它。

我有两个小脚本,parent.php并且child.php

这是代码parent.php

    $exe = $_SERVER['_'];
    $command = '/var/www/child.php';

    echo "\nSTART\n";

    $pid = pcntl_fork();

    ob_start();

    echo "\nHELLO\n";

    if ($pid == -1)
        exit("Could not fork");
    else if ($pid)
        pcntl_waitpid($pid, $status);
    else
    {
        $args = array
        (
            "arg1" => 'one',
            "arg2" => 'two',
            "arg3" => 'three'
        );

        pcntl_exec($exe, array($command), $args);
    }

    $content = ob_get_contents();
    ob_end_clean();

    echo "\nEND\n";

    echo $content . "\n";

这是代码child.php

    echo "\n\tHELLO FROM TEST\n";

    echo "\t"; var_dump($_SERVER['arg1']);
    echo "\t"; var_dump($_SERVER['arg2']);
    echo "\t"; var_dump($_SERVER['arg3']);

现在......这是我的输出:

START

    HELLO FROM TEST
    string(3) "one"
    string(3) "two"
    string(5) "three"

END

HELLO

但我需要这个输出

START

END

HELLO

    HELLO FROM TEST
    string(3) "one"
    string(3) "two"
    string(5) "three"

这可能是经典缓冲区解决方法ob_start()不起作用吗?

注意:输出的顺序并不重要,我需要捕获它以进行操作

4

1 回答 1

3

我找到了解决方案。

您必须使用允许您直接使用流缓冲区的proc_open()函数:

echo "\nSTART\n";

$stream = null;

$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("file", "/tmp/error-output.txt", "a")
);

$cwd = '/tmp';
$env = array('some_option' => 'aeiou');

$process = proc_open('/usr/bin/php', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process))
{
    fwrite($pipes[0], '<?php echo "HELLO FROM TEST"; ?>'); // here directly the code of child.php
    fclose($pipes[0]);

    $stream = stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    proc_close($process);
}

echo "\nEND\n";

echo "\n$stream\n";

输出是:

START

END

HELLO FROM TEST
于 2012-07-30T16:04:22.230 回答