我想在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
会立即返回,同时仍然向数组添加元素,并且有一个方法来检查进程是否已终止,则上述代码将起作用。
有办法吗?
答案 0 :(得分:1)
我通过将输出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);
}
}