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

问题描述:

我需要捕获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()经典的缓冲解决方法不起作用?

注:不输出的重要顺序,我需要捕捉到它的操作目的

我已经找到了解决办法。

必须使用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