PHP异步执行shell命令并检索实时输出

PHP异步执行shell命令并检索实时输出,php,exec,Php,Exec,我想在PHP中异步执行shell命令。也就是说,PHP不应该等到命令完成后才继续执行。然而,与关于Stackoverflow主题的众多问题相反,我确实关心程序的输出。我特别想做这样的事情: exec("some command", $output_array, $has_finished); while(count($output_array) > 0 && !$has_finished) { if(count($output_array) > 0)

我想在PHP中异步执行shell命令。也就是说,PHP不应该等到命令完成后才继续执行。然而,与关于Stackoverflow主题的众多问题相反,我确实关心程序的输出。我特别想做这样的事情:

exec("some command", $output_array, $has_finished);
while(count($output_array) > 0 && !$has_finished)
{
    if(count($output_array) > 0)
    {
        $line = array_shift($output_array);
        do_something_with_that($line);
    } else
        sleep(1);
}

do_something_with_that($line)
{
    echo $line."\n";
    flush();
}
如果
exec
在向数组添加元素的同时立即返回,并且有方法检查进程是否已终止,则上述代码将起作用


有没有办法做到这一点?

我已经解决了这个问题,将输出STDIN管道化到一个临时文件,然后从中读取

这是我的

实施 用法
或者类似地,您可以生成一个执行该操作的线程,并检查该线程的状态。可能有很多资源可以查看。但是,您不能使用本机PHP执行此操作,需要一个模块或库。@apokryfos是一个非常本机的PHP函数。Libs只是让使用它更方便一点。
class ExecAsync {

    public function __construct($cmd) {
        $this->cmd = $cmd;
        $this->cacheFile = ".cache-pipe-".uniqid();
        $this->lineNumber = 0;
    }

    public function getLine() {
        $file = new SplFileObject($this->cacheFile);
        $file->seek($this->lineNumber);
        if($file->valid())
        {
            $this->lineNumber++;
            $current = $file->current();
            return $current;
        } else
            return NULL;
    }

    public function hasFinished() {
        if(file_exists(".status-".$this->cacheFile) ||
            (!file_exists(".status-".$this->cacheFile) && !file_exists($this->cacheFile)))
        {
            unlink($this->cacheFile);
            unlink(".status-".$this->cacheFile);
            $this->lineNumber = 0;
            return TRUE;
        } else
            return FALSE;
    }

    public function run() {
        if($this->cmd) {
            $out = exec('{ '.$this->cmd." > ".$this->cacheFile." && echo finished > .status-".$this->cacheFile.";} > /dev/null 2>/dev/null &");
        }
    }
}
$command = new ExecAsync("command to execute");
//run the command
$command->run();
/*We want to read from the command output as long as
 *there are still lines left to read
 *and the command hasn't finished yet

 *if getLine returns NULL it means that we have caught up
 *and there are no more lines left to read
 */
while(($line = $command->getLine()) || !$command->hasFinished())
{
    if($line !== NULL)
    {
        echo $line."\n";
        flush();
    } else
    {
        usleep(10);
    }
}