如何在PHP输出的system()中逐行读取


How to read line by line in system() output by PHP

情况如下:我有一个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…)

一个好的解决方案是使用proc_open(),因为您可以使用所有管道。这里展示了一种不错的方法:http://codehackit.blogspot.be/2012/04/automating-command-line-scripts-in-php.html

我正在考虑每年输出一次该行的可能性行由控制台中的unix程序输出。

简单的句子-复杂的问题。这将涉及监视输出缓冲区或输出日志文件的更改,然后对此作出反应。事件绑定。尝试使用$proc->on()来检测输出缓冲区中的内容,以便触发回调。

引用:PHP中正确的shell执行;https://stackoverflow.com/a/1533818/1163786