我需要在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
但我需要THIS输出
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