如何在PHP中捕获捕获子进程输出

时间:2012-07-30 15:43:07

标签: php

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

我有两个小脚本,parent.phpchild.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()的经典缓冲区变通方法是否可行?

注意:输出顺序并不重要,我需要将其捕获以用于操作目的

1 个答案:

答案 0 :(得分: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