gpt4 book ai didi

php - 如何逐行读取 system() 输出的 PHP

转载 作者:搜寻专家 更新时间:2023-10-31 21:08:47 25 4
gpt4 key购买 nike

情况是这样的:我有一个 unix 程序,它输出一些行并且不会因为它持续监听而终止。现在我想在 PHP 脚本中输出这些行。我使用了 system() 函数,但它阻止了其余代码的运行,因为 unix 程序不会终止。我正在考虑一旦控制台中的unix程序输出一行就输出该行的可能性。我将如何实现这一目标?谢谢。

最佳答案

这是一个示例脚本,可以为您解决问题:

 $cmd='/bin/ls -la';
$gs="\n"; // this is the delimiter of each line. use "\r\n" in case of windows ...
$pipesDescr=array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("file", "/tmp/error.log", "a"), );
$p=proc_open($cmd, $pipesDescr, $pipes);
if ($p)
{
stream_set_blocking($pipes[0],0);
stream_set_blocking($pipes[1],0);
$work=true; $buffer=''; $mode='idle'; $command=''; $idle=0;
while ($work)
{
if ($mode=='idle')
{
if ($command<>'')
{
fwrite($pipes[0],$command."\n");
$command='';
$idle=0;
$speed=500; // microseconds!
}
else
{
$speed=100000; // microseconds !
}
}
$s=fread($pipes[1],1024);
if ($s<>'')
{
$mode='action';
$buffer.=$s;
while (strstr($buffer,$gs))
{
$ex=explode($gs,$buffer,2);
{
$buffer=@$ex[1]; $line=@$ex[0];
// here you can process the line with something ...
print($line."<br/>\n");
//
}
}
$speed=500;
$idle=0;
}
else
{
if (@$idle<1000)
{
$idle++; // did not idled for too long, let's still watch intensely for new data
}
else
{
$speed=100000; // it's been idle for a while, let's not overload the CPU for nothing ...
$mode='idle';
}
}
$status=proc_get_status($p);
if (!$status["running"]) {$work=false;} // if the program has quited, we should do so as well ...
} // end of $work loop
proc_close($p);
}

此示例使用 proc_open,并一直运行到您的进程终止,或直到您决定退出。 (在这种情况下,您应该将 $work 设置为 false ...)

关于php - 如何逐行读取 system() 输出的 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26695189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com