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

PHP Execute shell command asynchronously and retrieve live output

我想在 PHP 中异步执行 shell 命令。 IE。 PHP 不应等待命令完成才能继续执行。然而,与 Whosebug 上关于该主题的众多问题相比,我确实关心程序的输出。特别是我想做这样的事情:

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 会立即 return 同时仍然向数组中添加元素,并且如果有一种方法可以检查进程是否已终止,则上述代码将有效。

有办法吗?

我通过将输出 STDIN 传输到一个临时文件然后从中读取来解决了这个问题。

这是我的

实施

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);
    }
}