Process.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Process;
  11. /**
  12. * Process is a thin wrapper around proc_* functions to ease
  13. * start independent PHP processes.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. *
  17. * @api
  18. */
  19. class Process
  20. {
  21. private $commandline;
  22. private $cwd;
  23. private $env;
  24. private $stdin;
  25. private $timeout;
  26. private $options;
  27. private $exitcode;
  28. private $status;
  29. private $stdout;
  30. private $stderr;
  31. /**
  32. * Constructor.
  33. *
  34. * @param string $commandline The command line to run
  35. * @param string $cwd The working directory
  36. * @param array $env The environment variables
  37. * @param string $stdin The STDIN content
  38. * @param integer $timeout The timeout in seconds
  39. * @param array $options An array of options for proc_open
  40. *
  41. * @throws \RuntimeException When proc_open is not installed
  42. *
  43. * @api
  44. */
  45. public function __construct($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array())
  46. {
  47. if (!function_exists('proc_open')) {
  48. throw new \RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  49. }
  50. $this->commandline = $commandline;
  51. $this->cwd = $cwd;
  52. // on windows, if the cwd changed via chdir(), proc_open defaults to the dir where php was started
  53. if (null === $this->cwd && defined('PHP_WINDOWS_VERSION_BUILD')) {
  54. $this->cwd = getcwd();
  55. }
  56. if (null !== $env) {
  57. $this->env = array();
  58. foreach ($env as $key => $value) {
  59. $this->env[(binary) $key] = (binary) $value;
  60. }
  61. } else {
  62. $this->env = null;
  63. }
  64. $this->stdin = $stdin;
  65. $this->timeout = $timeout;
  66. $this->options = array_merge(array('suppress_errors' => true, 'binary_pipes' => true, 'bypass_shell' => false), $options);
  67. }
  68. /**
  69. * Runs the process.
  70. *
  71. * The callback receives the type of output (out or err) and
  72. * some bytes from the output in real-time. It allows to have feedback
  73. * from the independent process during execution.
  74. *
  75. * The STDOUT and STDERR are also available after the process is finished
  76. * via the getOutput() and getErrorOutput() methods.
  77. *
  78. * @param Closure|string|array $callback A PHP callback to run whenever there is some
  79. * output available on STDOUT or STDERR
  80. *
  81. * @return integer The exit status code
  82. *
  83. * @throws \RuntimeException When process can't be launch or is stopped
  84. *
  85. * @api
  86. */
  87. public function run($callback = null)
  88. {
  89. $this->stdout = '';
  90. $this->stderr = '';
  91. $that = $this;
  92. $callback = function ($type, $data) use ($that, $callback) {
  93. if ('out' == $type) {
  94. $that->addOutput($data);
  95. } else {
  96. $that->addErrorOutput($data);
  97. }
  98. if (null !== $callback) {
  99. call_user_func($callback, $type, $data);
  100. }
  101. };
  102. $descriptors = array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w'));
  103. $process = proc_open($this->commandline, $descriptors, $pipes, $this->cwd, $this->env, $this->options);
  104. if (!is_resource($process)) {
  105. throw new \RuntimeException('Unable to launch a new process.');
  106. }
  107. foreach ($pipes as $pipe) {
  108. stream_set_blocking($pipe, false);
  109. }
  110. if (null === $this->stdin) {
  111. fclose($pipes[0]);
  112. $writePipes = null;
  113. } else {
  114. $writePipes = array($pipes[0]);
  115. $stdinLen = strlen($this->stdin);
  116. $stdinOffset = 0;
  117. }
  118. unset($pipes[0]);
  119. while ($pipes || $writePipes) {
  120. $r = $pipes;
  121. $w = $writePipes;
  122. $e = null;
  123. $n = @stream_select($r, $w, $e, $this->timeout);
  124. if (false === $n) {
  125. break;
  126. } elseif ($n === 0) {
  127. proc_terminate($process);
  128. throw new \RuntimeException('The process timed out.');
  129. }
  130. if ($w) {
  131. $written = fwrite($writePipes[0], (binary) substr($this->stdin, $stdinOffset), 8192);
  132. if (false !== $written) {
  133. $stdinOffset += $written;
  134. }
  135. if ($stdinOffset >= $stdinLen) {
  136. fclose($writePipes[0]);
  137. $writePipes = null;
  138. }
  139. }
  140. foreach ($r as $pipe) {
  141. $type = array_search($pipe, $pipes);
  142. $data = fread($pipe, 8192);
  143. if (strlen($data) > 0) {
  144. call_user_func($callback, $type == 1 ? 'out' : 'err', $data);
  145. }
  146. if (false === $data || feof($pipe)) {
  147. fclose($pipe);
  148. unset($pipes[$type]);
  149. }
  150. }
  151. }
  152. $this->status = proc_get_status($process);
  153. $time = 0;
  154. while (1 == $this->status['running'] && $time < 1000000) {
  155. $time += 1000;
  156. usleep(1000);
  157. $this->status = proc_get_status($process);
  158. }
  159. $exitcode = proc_close($process);
  160. if ($this->status['signaled']) {
  161. throw new \RuntimeException(sprintf('The process stopped because of a "%s" signal.', $this->status['stopsig']));
  162. }
  163. return $this->exitcode = $this->status['running'] ? $exitcode : $this->status['exitcode'];
  164. }
  165. /**
  166. * Returns the output of the process (STDOUT).
  167. *
  168. * This only returns the output if you have not supplied a callback
  169. * to the run() method.
  170. *
  171. * @return string The process output
  172. *
  173. * @api
  174. */
  175. public function getOutput()
  176. {
  177. return $this->stdout;
  178. }
  179. /**
  180. * Returns the error output of the process (STDERR).
  181. *
  182. * This only returns the error output if you have not supplied a callback
  183. * to the run() method.
  184. *
  185. * @return string The process error output
  186. *
  187. * @api
  188. */
  189. public function getErrorOutput()
  190. {
  191. return $this->stderr;
  192. }
  193. /**
  194. * Returns the exit code returned by the process.
  195. *
  196. * @return integer The exit status code
  197. *
  198. * @api
  199. */
  200. public function getExitCode()
  201. {
  202. return $this->exitcode;
  203. }
  204. /**
  205. * Checks if the process ended successfully.
  206. *
  207. * @return Boolean true if the process ended successfully, false otherwise
  208. *
  209. * @api
  210. */
  211. public function isSuccessful()
  212. {
  213. return 0 == $this->exitcode;
  214. }
  215. /**
  216. * Returns true if the child process has been terminated by an uncaught signal.
  217. *
  218. * It always returns false on Windows.
  219. *
  220. * @return Boolean
  221. *
  222. * @api
  223. */
  224. public function hasBeenSignaled()
  225. {
  226. return $this->status['signaled'];
  227. }
  228. /**
  229. * Returns the number of the signal that caused the child process to terminate its execution.
  230. *
  231. * It is only meaningful if hasBeenSignaled() returns true.
  232. *
  233. * @return integer
  234. *
  235. * @api
  236. */
  237. public function getTermSignal()
  238. {
  239. return $this->status['termsig'];
  240. }
  241. /**
  242. * Returns true if the child process has been stopped by a signal.
  243. *
  244. * It always returns false on Windows.
  245. *
  246. * @return Boolean
  247. *
  248. * @api
  249. */
  250. public function hasBeenStopped()
  251. {
  252. return $this->status['stopped'];
  253. }
  254. /**
  255. * Returns the number of the signal that caused the child process to stop its execution.
  256. *
  257. * It is only meaningful if hasBeenStopped() returns true.
  258. *
  259. * @return integer
  260. *
  261. * @api
  262. */
  263. public function getStopSignal()
  264. {
  265. return $this->status['stopsig'];
  266. }
  267. /**
  268. * Adds a line to the STDOUT stream.
  269. *
  270. * @param string $line The line to append
  271. */
  272. public function addOutput($line)
  273. {
  274. $this->stdout .= $line;
  275. }
  276. /**
  277. * Adds a line to the STDERR stream.
  278. *
  279. * @param string $line The line to append
  280. */
  281. public function addErrorOutput($line)
  282. {
  283. $this->stderr .= $line;
  284. }
  285. /**
  286. * Gets the command line to be executed.
  287. *
  288. * @return string The command to execute
  289. */
  290. public function getCommandLine()
  291. {
  292. return $this->commandline;
  293. }
  294. /**
  295. * Sets the command line to be executed.
  296. *
  297. * @param string $commandline The command to execute
  298. */
  299. public function setCommandLine($commandline)
  300. {
  301. $this->commandline = $commandline;
  302. }
  303. /**
  304. * Gets the process timeout.
  305. *
  306. * @return integer The timeout in seconds
  307. */
  308. public function getTimeout()
  309. {
  310. return $this->timeout;
  311. }
  312. /**
  313. * Sets the process timeout.
  314. *
  315. * @param integer|null $timeout The timeout in seconds
  316. */
  317. public function setTimeout($timeout)
  318. {
  319. $this->timeout = $timeout;
  320. }
  321. /**
  322. * Gets the working directory.
  323. *
  324. * @return string The current working directory
  325. */
  326. public function getWorkingDirectory()
  327. {
  328. // This is for BC only
  329. if (null === $this->cwd) {
  330. // getcwd() will return false if any one of the parent directories does not have
  331. // the readable or search mode set, even if the current directory does
  332. return getcwd() ?: null;
  333. }
  334. return $this->cwd;
  335. }
  336. /**
  337. * Sets the current working directory.
  338. *
  339. * @param string $cwd The new working directory
  340. */
  341. public function setWorkingDirectory($cwd)
  342. {
  343. $this->cwd = $cwd;
  344. }
  345. /**
  346. * Gets the environment variables.
  347. *
  348. * @return array The current environment variables
  349. */
  350. public function getEnv()
  351. {
  352. return $this->env;
  353. }
  354. /**
  355. * Sets the environment variables.
  356. *
  357. * @param array $env The new environment variables
  358. */
  359. public function setEnv(array $env)
  360. {
  361. $this->env = $env;
  362. }
  363. /**
  364. * Gets the contents of STDIN.
  365. *
  366. * @return string The current contents
  367. */
  368. public function getStdin()
  369. {
  370. return $this->stdin;
  371. }
  372. /**
  373. * Sets the contents of STDIN.
  374. *
  375. * @param string $stdin The new contents
  376. */
  377. public function setStdin($stdin)
  378. {
  379. $this->stdin = $stdin;
  380. }
  381. /**
  382. * Gets the options for proc_open.
  383. *
  384. * @return array The current options
  385. */
  386. public function getOptions()
  387. {
  388. return $this->options;
  389. }
  390. /**
  391. * Sets the options for proc_open.
  392. *
  393. * @param array $options The new options
  394. */
  395. public function setOptions(array $options)
  396. {
  397. $this->options = $options;
  398. }
  399. }