composer require "symfony/process:2.7.1"
##描述 process組件是能夠開啓一個子進程 去執行一個命令 ##例子 use Symfony\Component\Process\Process; $process = new Process('ls -lsa'); $process->run(); // executes after the command finishes if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } echo $process->getOutput();windows
實時輸出命令的輸出composer
use Symfony\Component\Process\Process; $process = new Process('ls -lsa'); $process->run(function ($type, $buffer) { if (Process::ERR === $type) { echo 'ERR > '.$buffer; } else { echo 'OUT > '.$buffer; } });
異步執行異步
$process = new Process('ls -lsa'); $process->start(); //在這裏開啓一個子進程去執行 // ... do other things //必定要調用wait方法;要否則上面的子進程會成爲一個殭屍進程 $process->wait(function ($type, $buffer) { if (Process::ERR === $type) { echo 'ERR > '.$buffer; } else { echo 'OUT > '.$buffer; } });
中止進程 $process->stop(3, SIGINT);
設置超時時間 $process->setTimeout(3600);
發送一個信號(windows系統無效) $process->signal(SIGKILL);
設置閒置超時(即命令沒有輸出) $process->setIdleTimeout(60);命令60s沒有輸出東西就會超時
若是超時會拋出 RuntimeException 異常ui
##未明白的問題code
在文檔中有一個ProcessBuilder類用來建立一個跨平臺命令;可是有點不理解官方的給的例子symfony
use Symfony\Component\Process\ProcessBuilder; $builder = new ProcessBuilder(); $builder->setPrefix('/usr/bin/tar'); // '/usr/bin/tar' '--list' '--file=archive.tar.gz' 就是不明白爲何會輸出這樣的字符串; echo $builder ->setArguments(array('--list', '--file=archive.tar.gz')) ->getProcess() ->getCommandLine(); // '/usr/bin/tar' '-xzf' 'archive.tar.gz' echo $builder ->setArguments(array('-xzf', 'archive.tar.gz')) ->getProcess() ->getCommandLine();