首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP异步执行shell命令并检索实时输出

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

Stack Overflow用户
提问于 2017-02-14 18:46:00
回答 1查看 1.8K关注 0票数 1

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

代码语言:javascript
复制
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在继续向数组添加元素的同时立即返回,并且是否有方法检查进程是否已终止,则上面的代码可以正常工作。

有没有办法做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-24 16:09:34

我已经解决了这个问题,方法是将输出STDIN通过管道传输到一个临时文件,然后从该文件中读取数据。

这是我的

实现

代码语言:javascript
复制
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 &");
        }
    }
}

用法

代码语言:javascript
复制
$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);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42224107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档