使用PHP shell_exec,使输出为;管道;不是";“倾销”;
快速提问真的 考虑以下代码:使用PHP shell_exec,使输出为;管道;不是";“倾销”;,php,exec,shell-exec,command-line-interface,passthru,Php,Exec,Shell Exec,Command Line Interface,Passthru,快速提问真的 考虑以下代码: //__/var/test/cli_test.php__ $x = 0; while ($x < 9){ print "loop " . str_pad($x, 3, "0", STR_PAD_LEFT) . "\n"; sleep(1); $x++; } 现在考虑一个不同的命题 //__/var/test/cli_test_shell.php print shell_exec("php /var/test/cli_test.php"); 如果
//__/var/test/cli_test.php__
$x = 0;
while ($x < 9){
print "loop " . str_pad($x, 3, "0", STR_PAD_LEFT) . "\n";
sleep(1);
$x++;
}
现在考虑一个不同的命题
//__/var/test/cli_test_shell.php
print shell_exec("php /var/test/cli_test.php");
如果我在命令行中键入php/var/test/cli\u test\u shell.php
,我会在9秒钟内一无所获,然后一切都会到来。。i、 e.1大输出1大等待。等了9秒钟,什么都没有了。。然后转储:
loop 000
loop 001
loop 002
loop 003
loop 004
loop 005
loop 006
loop 007
loop 008
如何更改
/var/test/cli\u test\u shell.php
,使输出每秒返回每一行使用shell\u exec()
无法实现所需的行为。这是因为函数收集命令的输出,并在命令终止后将其作为字符串返回。改为使用并保持原样。尝试以下方法:
$handle = popen('php /var/test/cli_test_shell.php 2>&1', 'r');
while (!feof($handle)) {
echo fread($handle, 8192);
}
fclose($handle);
谢谢:)但是你读错了,问题是“我如何修改/var/test/cli\u test\u shell.php”。。您可能会注意到我已经“标记”了passthru(),我不相信它在没有ob_flush()的情况下会正常工作。您知道它应该如何与shell_exec()一起工作吗
print
将在shell_exec()
返回后执行。shell_exec
/exec
/passthru
这都是一个相同的问题,问题是如何更改它以获得9条管道“活动”,我最好的猜测是,它是一个exec
,在$output上有一个ob\u flush回调,但我不知道如何优雅地实现它。。。如果希望在变量中同时包含即时输出和输出,可以使用popen()或proc_open()。你可以完全控制管道,然后检查我的答案,它可以工作;)我用这个disable_ob()
修复了它,很高兴你找到了解决方案;)
$handle = popen('php /var/test/cli_test_shell.php 2>&1', 'r');
while (!feof($handle)) {
echo fread($handle, 8192);
}
fclose($handle);