问题
我正在使用一个proc_open()
用于调用 shell 命令的函数。看来我做 STDIO 的方式是错误的,有时会导致 PHP 或目标命令锁定。这是原始代码:
function execute($cmd, $stdin=null){
$proc=proc_open($cmd,array(0=>array('pipe','r'),1=>array('pipe','w'),2=>array('pipe','w')),$pipes);
fwrite($pipes[0],$stdin); fclose($pipes[0]);
$stdout=stream_get_contents($pipes[1]); fclose($pipes[1]);
$stderr=stream_get_contents($pipes[2]); fclose($pipes[2]);
return array( 'stdout'=>$stdout, 'stderr'=>$stderr, 'return'=>proc_close($proc) );
}
它大部分时间都有效,但这还不够,我想让它一直有效。
如果 STDIO 缓冲区超过 4k 的数据,问题就在于stream_get_contents()
锁定。
测试用例
function out($data){
file_put_contents('php://stdout',$data);
}
function err($data){
file_put_contents('php://stderr',$data);
}
if(isset($argc)){
// RUN CLI TESTCASE
out(str_repeat('o',1030);
err(str_repeat('e',1030);
out(str_repeat('O',1030);
err(str_repeat('E',1030);
die(128); // to test return error code
}else{
// RUN EXECUTION TEST CASE
$res=execute('php -f '.escapeshellarg(__FILE__));
}
我们两次向 STDERR 和 STDOUT 输出一个字符串,总长度为 4120 字节(超过 4k)。这会导致 PHP 在两边都锁定。
解决方案
显然,stream_select()
是要走的路。我有以下代码:
function execute($cmd,$stdin=null,$timeout=20000){
$proc=proc_open($cmd,array(0=>array('pipe','r'),1=>array('pipe','w'),2=>array('pipe','w')),$pipes);
$write = array($pipes[0]);
$read = array($pipes[1], $pipes[2]);
$except = null;
$stdout = '';
$stderr = '';
while($r = stream_select($read, $write, $except, null, $timeout)){
foreach($read as $stream){
// handle STDOUT
if($stream===$pipes[1])
/*...*/ $stdout.=stream_get_contents($stream);
// handle STDERR
if($stream===$pipes[2])
/*...*/ $stderr.=stream_get_contents($stream);
}
// Handle STDIN (???)
if(isset($write[0])) ;
// the following code is temporary
$n=isset($n) ? $n+1 : 0; if($n>10)break; // break while loop after 10 iterations
}
}
剩下的唯一一块拼图是处理 STDIN(见标有 的行(???)
)。
我发现 STDIN 必须由调用我的函数的任何东西提供,execute()
. 但是如果我根本不想使用 STDIN 怎么办?在上面的测试用例中,我没有要求输入,但我应该对 STDIN 做点什么。
也就是说,上述方法仍然冻结在stream_get_contents()
. 我很不确定下一步该做什么/尝试。
学分
Jakob Truelsen 提出了解决方案,并发现了原始问题。4k 小费也是他的主意。在此之前,我对为什么该函数工作正常感到困惑(不知道这完全取决于缓冲区大小)。