4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Process;
14 use Symfony\Component\Process\Exception\InvalidArgumentException;
15 use Symfony\Component\Process\Exception\LogicException;
16 use Symfony\Component\Process\Exception\ProcessFailedException;
17 use Symfony\Component\Process\Exception\ProcessTimedOutException;
18 use Symfony\Component\Process\Exception\RuntimeException;
19 use Symfony\Component\Process\Pipes\PipesInterface;
20 use Symfony\Component\Process\Pipes\UnixPipes;
21 use Symfony\Component\Process\Pipes\WindowsPipes;
24 * Process is a thin wrapper around proc_* functions to easily
25 * start independent PHP processes.
27 * @author Fabien Potencier <fabien@symfony.com>
28 * @author Romain Neutron <imprec@gmail.com>
35 const STATUS_READY = 'ready';
36 const STATUS_STARTED = 'started';
37 const STATUS_TERMINATED = 'terminated';
43 // Timeout Precision in seconds.
44 const TIMEOUT_PRECISION = 0.2;
52 private $lastOutputTime;
57 private $fallbackStatus = array();
58 private $processInformation;
59 private $outputDisabled = false;
62 private $enhanceWindowsCompatibility = true;
63 private $enhanceSigchildCompatibility;
65 private $status = self::STATUS_READY;
66 private $incrementalOutputOffset = 0;
67 private $incrementalErrorOutputOffset = 0;
71 private $useFileHandles = false;
72 /** @var PipesInterface */
73 private $processPipes;
75 private $latestSignal;
77 private static $sigchild;
80 * Exit codes translation table.
82 * User-defined errors must use exit codes in the 64-113 range.
86 public static $exitCodes = array(
89 2 => 'Misuse of shell builtins',
91 126 => 'Invoked command cannot execute',
92 127 => 'Command not found',
93 128 => 'Invalid exit argument',
98 131 => 'Quit and dump core',
99 132 => 'Illegal instruction',
100 133 => 'Trace/breakpoint trap',
101 134 => 'Process aborted',
102 135 => 'Bus error: "access to undefined portion of memory object"',
103 136 => 'Floating point exception: "erroneous arithmetic operation"',
104 137 => 'Kill (terminate immediately)',
105 138 => 'User-defined 1',
106 139 => 'Segmentation violation',
107 140 => 'User-defined 2',
108 141 => 'Write to pipe with no one reading',
109 142 => 'Signal raised by alarm',
110 143 => 'Termination (request to terminate)',
112 145 => 'Child process terminated, stopped (or continued*)',
113 146 => 'Continue if stopped',
114 147 => 'Stop executing temporarily',
115 148 => 'Terminal stop signal',
116 149 => 'Background process attempting to read from tty ("in")',
117 150 => 'Background process attempting to write to tty ("out")',
118 151 => 'Urgent data available on socket',
119 152 => 'CPU time limit exceeded',
120 153 => 'File size limit exceeded',
121 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
122 155 => 'Profiling timer expired',
124 157 => 'Pollable event',
126 159 => 'Bad syscall',
132 * @param string $commandline The command line to run
133 * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
134 * @param array|null $env The environment variables or null to use the same environment as the current PHP process
135 * @param string|null $input The input
136 * @param int|float|null $timeout The timeout in seconds or null to disable
137 * @param array $options An array of options for proc_open
139 * @throws RuntimeException When proc_open is not installed
141 public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
143 if (!function_exists('proc_open')) {
144 throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
147 $this->commandline = $commandline;
150 // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
151 // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
152 // @see : https://bugs.php.net/bug.php?id=51800
153 // @see : https://bugs.php.net/bug.php?id=50524
154 if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
155 $this->cwd = getcwd();
161 $this->setInput($input);
162 $this->setTimeout($timeout);
163 $this->useFileHandles = '\\' === DIRECTORY_SEPARATOR;
165 $this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
166 $this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options);
169 public function __destruct()
174 public function __clone()
176 $this->resetProcessData();
182 * The callback receives the type of output (out or err) and
183 * some bytes from the output in real-time. It allows to have feedback
184 * from the independent process during execution.
186 * The STDOUT and STDERR are also available after the process is finished
187 * via the getOutput() and getErrorOutput() methods.
189 * @param callable|null $callback A PHP callback to run whenever there is some
190 * output available on STDOUT or STDERR
192 * @return int The exit status code
194 * @throws RuntimeException When process can't be launched
195 * @throws RuntimeException When process stopped after receiving signal
196 * @throws LogicException In case a callback is provided and output has been disabled
198 public function run($callback = null)
200 $this->start($callback);
202 return $this->wait();
208 * This is identical to run() except that an exception is thrown if the process
209 * exits with a non-zero exit code.
211 * @param callable|null $callback
215 * @throws RuntimeException if PHP was compiled with --enable-sigchild and the enhanced sigchild compatibility mode is not enabled
216 * @throws ProcessFailedException if the process didn't terminate successfully
218 public function mustRun($callback = null)
220 if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
221 throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
224 if (0 !== $this->run($callback)) {
225 throw new ProcessFailedException($this);
232 * Starts the process and returns after writing the input to STDIN.
234 * This method blocks until all STDIN data is sent to the process then it
235 * returns while the process runs in the background.
237 * The termination of the process can be awaited with wait().
239 * The callback receives the type of output (out or err) and some bytes from
240 * the output in real-time while writing the standard input to the process.
241 * It allows to have feedback from the independent process during execution.
243 * @param callable|null $callback A PHP callback to run whenever there is some
244 * output available on STDOUT or STDERR
246 * @throws RuntimeException When process can't be launched
247 * @throws RuntimeException When process is already running
248 * @throws LogicException In case a callback is provided and output has been disabled
250 public function start($callback = null)
252 if ($this->isRunning()) {
253 throw new RuntimeException('Process is already running');
255 if ($this->outputDisabled && null !== $callback) {
256 throw new LogicException('Output has been disabled, enable it to allow the use of a callback.');
259 $this->resetProcessData();
260 $this->starttime = $this->lastOutputTime = microtime(true);
261 $this->callback = $this->buildCallback($callback);
262 $descriptors = $this->getDescriptors();
264 $commandline = $this->commandline;
266 if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
267 $commandline = 'cmd /V:ON /E:ON /D /C "('.$commandline.')';
268 foreach ($this->processPipes->getFiles() as $offset => $filename) {
269 $commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename);
273 if (!isset($this->options['bypass_shell'])) {
274 $this->options['bypass_shell'] = true;
276 } elseif (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
277 // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
278 $descriptors[3] = array('pipe', 'w');
280 // See https://unix.stackexchange.com/questions/71205/background-process-pipe-input
281 $commandline = '{ ('.$this->commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';
282 $commandline .= 'pid=$!; echo $pid >&3; wait $pid; code=$?; echo $code >&3; exit $code';
284 // Workaround for the bug, when PTS functionality is enabled.
285 // @see : https://bugs.php.net/69442
286 $ptsWorkaround = fopen(__FILE__, 'r');
289 $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
291 if (!is_resource($this->process)) {
292 throw new RuntimeException('Unable to launch a new process.');
294 $this->status = self::STATUS_STARTED;
296 if (isset($descriptors[3])) {
297 $this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]);
304 $this->updateStatus(false);
305 $this->checkTimeout();
309 * Restarts the process.
311 * Be warned that the process is cloned before being started.
313 * @param callable|null $callback A PHP callback to run whenever there is some
314 * output available on STDOUT or STDERR
318 * @throws RuntimeException When process can't be launched
319 * @throws RuntimeException When process is already running
323 public function restart($callback = null)
325 if ($this->isRunning()) {
326 throw new RuntimeException('Process is already running');
329 $process = clone $this;
330 $process->start($callback);
336 * Waits for the process to terminate.
338 * The callback receives the type of output (out or err) and some bytes
339 * from the output in real-time while writing the standard input to the process.
340 * It allows to have feedback from the independent process during execution.
342 * @param callable|null $callback A valid PHP callback
344 * @return int The exitcode of the process
346 * @throws RuntimeException When process timed out
347 * @throws RuntimeException When process stopped after receiving signal
348 * @throws LogicException When process is not yet started
350 public function wait($callback = null)
352 $this->requireProcessIsStarted(__FUNCTION__);
354 $this->updateStatus(false);
355 if (null !== $callback) {
356 $this->callback = $this->buildCallback($callback);
360 $this->checkTimeout();
361 $running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
362 $this->readPipes($running, '\\' !== DIRECTORY_SEPARATOR || !$running);
365 while ($this->isRunning()) {
369 if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
370 throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
373 return $this->exitcode;
377 * Returns the Pid (process identifier), if applicable.
379 * @return int|null The process id if running, null otherwise
381 public function getPid()
383 return $this->isRunning() ? $this->processInformation['pid'] : null;
387 * Sends a POSIX signal to the process.
389 * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
393 * @throws LogicException In case the process is not running
394 * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
395 * @throws RuntimeException In case of failure
397 public function signal($signal)
399 $this->doSignal($signal, true);
405 * Disables fetching output and error output from the underlying process.
409 * @throws RuntimeException In case the process is already running
410 * @throws LogicException if an idle timeout is set
412 public function disableOutput()
414 if ($this->isRunning()) {
415 throw new RuntimeException('Disabling output while the process is running is not possible.');
417 if (null !== $this->idleTimeout) {
418 throw new LogicException('Output can not be disabled while an idle timeout is set.');
421 $this->outputDisabled = true;
427 * Enables fetching output and error output from the underlying process.
431 * @throws RuntimeException In case the process is already running
433 public function enableOutput()
435 if ($this->isRunning()) {
436 throw new RuntimeException('Enabling output while the process is running is not possible.');
439 $this->outputDisabled = false;
445 * Returns true in case the output is disabled, false otherwise.
449 public function isOutputDisabled()
451 return $this->outputDisabled;
455 * Returns the current output of the process (STDOUT).
457 * @return string The process output
459 * @throws LogicException in case the output has been disabled
460 * @throws LogicException In case the process is not started
462 public function getOutput()
464 $this->readPipesForOutput(__FUNCTION__);
466 if (false === $ret = stream_get_contents($this->stdout, -1, 0)) {
474 * Returns the output incrementally.
476 * In comparison with the getOutput method which always return the whole
477 * output, this one returns the new output since the last call.
479 * @return string The process output since the last call
481 * @throws LogicException in case the output has been disabled
482 * @throws LogicException In case the process is not started
484 public function getIncrementalOutput()
486 $this->readPipesForOutput(__FUNCTION__);
488 $latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
489 $this->incrementalOutputOffset = ftell($this->stdout);
491 if (false === $latest) {
499 * Clears the process output.
503 public function clearOutput()
505 ftruncate($this->stdout, 0);
506 fseek($this->stdout, 0);
507 $this->incrementalOutputOffset = 0;
513 * Returns the current error output of the process (STDERR).
515 * @return string The process error output
517 * @throws LogicException in case the output has been disabled
518 * @throws LogicException In case the process is not started
520 public function getErrorOutput()
522 $this->readPipesForOutput(__FUNCTION__);
524 if (false === $ret = stream_get_contents($this->stderr, -1, 0)) {
532 * Returns the errorOutput incrementally.
534 * In comparison with the getErrorOutput method which always return the
535 * whole error output, this one returns the new error output since the last
538 * @return string The process error output since the last call
540 * @throws LogicException in case the output has been disabled
541 * @throws LogicException In case the process is not started
543 public function getIncrementalErrorOutput()
545 $this->readPipesForOutput(__FUNCTION__);
547 $latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
548 $this->incrementalErrorOutputOffset = ftell($this->stderr);
550 if (false === $latest) {
558 * Clears the process output.
562 public function clearErrorOutput()
564 ftruncate($this->stderr, 0);
565 fseek($this->stderr, 0);
566 $this->incrementalErrorOutputOffset = 0;
572 * Returns the exit code returned by the process.
574 * @return null|int The exit status code, null if the Process is not terminated
576 * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
578 public function getExitCode()
580 if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
581 throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
584 $this->updateStatus(false);
586 return $this->exitcode;
590 * Returns a string representation for the exit code returned by the process.
592 * This method relies on the Unix exit code status standardization
593 * and might not be relevant for other operating systems.
595 * @return null|string A string representation for the exit status code, null if the Process is not terminated
597 * @see http://tldp.org/LDP/abs/html/exitcodes.html
598 * @see http://en.wikipedia.org/wiki/Unix_signal
600 public function getExitCodeText()
602 if (null === $exitcode = $this->getExitCode()) {
606 return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
610 * Checks if the process ended successfully.
612 * @return bool true if the process ended successfully, false otherwise
614 public function isSuccessful()
616 return 0 === $this->getExitCode();
620 * Returns true if the child process has been terminated by an uncaught signal.
622 * It always returns false on Windows.
626 * @throws RuntimeException In case --enable-sigchild is activated
627 * @throws LogicException In case the process is not terminated
629 public function hasBeenSignaled()
631 $this->requireProcessIsTerminated(__FUNCTION__);
633 if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
634 throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
637 return $this->processInformation['signaled'];
641 * Returns the number of the signal that caused the child process to terminate its execution.
643 * It is only meaningful if hasBeenSignaled() returns true.
647 * @throws RuntimeException In case --enable-sigchild is activated
648 * @throws LogicException In case the process is not terminated
650 public function getTermSignal()
652 $this->requireProcessIsTerminated(__FUNCTION__);
654 if ($this->isSigchildEnabled() && (!$this->enhanceSigchildCompatibility || -1 === $this->processInformation['termsig'])) {
655 throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
658 return $this->processInformation['termsig'];
662 * Returns true if the child process has been stopped by a signal.
664 * It always returns false on Windows.
668 * @throws LogicException In case the process is not terminated
670 public function hasBeenStopped()
672 $this->requireProcessIsTerminated(__FUNCTION__);
674 return $this->processInformation['stopped'];
678 * Returns the number of the signal that caused the child process to stop its execution.
680 * It is only meaningful if hasBeenStopped() returns true.
684 * @throws LogicException In case the process is not terminated
686 public function getStopSignal()
688 $this->requireProcessIsTerminated(__FUNCTION__);
690 return $this->processInformation['stopsig'];
694 * Checks if the process is currently running.
696 * @return bool true if the process is currently running, false otherwise
698 public function isRunning()
700 if (self::STATUS_STARTED !== $this->status) {
704 $this->updateStatus(false);
706 return $this->processInformation['running'];
710 * Checks if the process has been started with no regard to the current state.
712 * @return bool true if status is ready, false otherwise
714 public function isStarted()
716 return $this->status != self::STATUS_READY;
720 * Checks if the process is terminated.
722 * @return bool true if process is terminated, false otherwise
724 public function isTerminated()
726 $this->updateStatus(false);
728 return $this->status == self::STATUS_TERMINATED;
732 * Gets the process status.
734 * The status is one of: ready, started, terminated.
736 * @return string The current process status
738 public function getStatus()
740 $this->updateStatus(false);
742 return $this->status;
748 * @param int|float $timeout The timeout in seconds
749 * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9)
751 * @return int The exit-code of the process
753 public function stop($timeout = 10, $signal = null)
755 $timeoutMicro = microtime(true) + $timeout;
756 if ($this->isRunning()) {
757 // given `SIGTERM` may not be defined and that `proc_terminate` uses the constant value and not the constant itself, we use the same here
758 $this->doSignal(15, false);
761 } while ($this->isRunning() && microtime(true) < $timeoutMicro);
763 if ($this->isRunning()) {
764 // Avoid exception here: process is supposed to be running, but it might have stopped just
765 // after this line. In any case, let's silently discard the error, we cannot do anything.
766 $this->doSignal($signal ?: 9, false);
770 if ($this->isRunning()) {
771 if (isset($this->fallbackStatus['pid'])) {
772 unset($this->fallbackStatus['pid']);
774 return $this->stop(0, $signal);
779 return $this->exitcode;
783 * Adds a line to the STDOUT stream.
787 * @param string $line The line to append
789 public function addOutput($line)
791 $this->lastOutputTime = microtime(true);
793 fseek($this->stdout, 0, SEEK_END);
794 fwrite($this->stdout, $line);
795 fseek($this->stdout, $this->incrementalOutputOffset);
799 * Adds a line to the STDERR stream.
803 * @param string $line The line to append
805 public function addErrorOutput($line)
807 $this->lastOutputTime = microtime(true);
809 fseek($this->stderr, 0, SEEK_END);
810 fwrite($this->stderr, $line);
811 fseek($this->stderr, $this->incrementalErrorOutputOffset);
815 * Gets the command line to be executed.
817 * @return string The command to execute
819 public function getCommandLine()
821 return $this->commandline;
825 * Sets the command line to be executed.
827 * @param string $commandline The command to execute
829 * @return self The current Process instance
831 public function setCommandLine($commandline)
833 $this->commandline = $commandline;
839 * Gets the process timeout (max. runtime).
841 * @return float|null The timeout in seconds or null if it's disabled
843 public function getTimeout()
845 return $this->timeout;
849 * Gets the process idle timeout (max. time since last output).
851 * @return float|null The timeout in seconds or null if it's disabled
853 public function getIdleTimeout()
855 return $this->idleTimeout;
859 * Sets the process timeout (max. runtime).
861 * To disable the timeout, set this value to null.
863 * @param int|float|null $timeout The timeout in seconds
865 * @return self The current Process instance
867 * @throws InvalidArgumentException if the timeout is negative
869 public function setTimeout($timeout)
871 $this->timeout = $this->validateTimeout($timeout);
877 * Sets the process idle timeout (max. time since last output).
879 * To disable the timeout, set this value to null.
881 * @param int|float|null $timeout The timeout in seconds
883 * @return self The current Process instance
885 * @throws LogicException if the output is disabled
886 * @throws InvalidArgumentException if the timeout is negative
888 public function setIdleTimeout($timeout)
890 if (null !== $timeout && $this->outputDisabled) {
891 throw new LogicException('Idle timeout can not be set while the output is disabled.');
894 $this->idleTimeout = $this->validateTimeout($timeout);
900 * Enables or disables the TTY mode.
902 * @param bool $tty True to enabled and false to disable
904 * @return self The current Process instance
906 * @throws RuntimeException In case the TTY mode is not supported
908 public function setTty($tty)
910 if ('\\' === DIRECTORY_SEPARATOR && $tty) {
911 throw new RuntimeException('TTY mode is not supported on Windows platform.');
914 static $isTtySupported;
916 if (null === $isTtySupported) {
917 $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', array(array('file', '/dev/tty', 'r'), array('file', '/dev/tty', 'w'), array('file', '/dev/tty', 'w')), $pipes);
920 if (!$isTtySupported) {
921 throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');
925 $this->tty = (bool) $tty;
931 * Checks if the TTY mode is enabled.
933 * @return bool true if the TTY mode is enabled, false otherwise
935 public function isTty()
947 public function setPty($bool)
949 $this->pty = (bool) $bool;
959 public function isPty()
965 * Gets the working directory.
967 * @return string|null The current working directory or null on failure
969 public function getWorkingDirectory()
971 if (null === $this->cwd) {
972 // getcwd() will return false if any one of the parent directories does not have
973 // the readable or search mode set, even if the current directory does
974 return getcwd() ?: null;
981 * Sets the current working directory.
983 * @param string $cwd The new working directory
985 * @return self The current Process instance
987 public function setWorkingDirectory($cwd)
995 * Gets the environment variables.
997 * @return array The current environment variables
999 public function getEnv()
1005 * Sets the environment variables.
1007 * An environment variable value should be a string.
1008 * If it is an array, the variable is ignored.
1010 * That happens in PHP when 'argv' is registered into
1011 * the $_ENV array for instance.
1013 * @param array $env The new environment variables
1015 * @return self The current Process instance
1017 public function setEnv(array $env)
1019 // Process can not handle env values that are arrays
1020 $env = array_filter($env, function ($value) {
1021 return !is_array($value);
1024 $this->env = array();
1025 foreach ($env as $key => $value) {
1026 $this->env[$key] = (string) $value;
1033 * Gets the contents of STDIN.
1035 * @return string|null The current contents
1037 * @deprecated since version 2.5, to be removed in 3.0.
1038 * Use setInput() instead.
1039 * This method is deprecated in favor of getInput.
1041 public function getStdin()
1043 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.5 and will be removed in 3.0. Use the getInput() method instead.', E_USER_DEPRECATED);
1045 return $this->getInput();
1049 * Gets the Process input.
1051 * @return null|string The Process input
1053 public function getInput()
1055 return $this->input;
1059 * Sets the contents of STDIN.
1061 * @param string|null $stdin The new contents
1063 * @return self The current Process instance
1065 * @deprecated since version 2.5, to be removed in 3.0.
1066 * Use setInput() instead.
1068 * @throws LogicException In case the process is running
1069 * @throws InvalidArgumentException In case the argument is invalid
1071 public function setStdin($stdin)
1073 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.5 and will be removed in 3.0. Use the setInput() method instead.', E_USER_DEPRECATED);
1075 return $this->setInput($stdin);
1081 * This content will be passed to the underlying process standard input.
1083 * @param mixed $input The content
1085 * @return self The current Process instance
1087 * @throws LogicException In case the process is running
1089 * Passing an object as an input is deprecated since version 2.5 and will be removed in 3.0.
1091 public function setInput($input)
1093 if ($this->isRunning()) {
1094 throw new LogicException('Input can not be set while the process is running.');
1097 $this->input = ProcessUtils::validateInput(__METHOD__, $input);
1103 * Gets the options for proc_open.
1105 * @return array The current options
1107 public function getOptions()
1109 return $this->options;
1113 * Sets the options for proc_open.
1115 * @param array $options The new options
1117 * @return self The current Process instance
1119 public function setOptions(array $options)
1121 $this->options = $options;
1127 * Gets whether or not Windows compatibility is enabled.
1129 * This is true by default.
1133 public function getEnhanceWindowsCompatibility()
1135 return $this->enhanceWindowsCompatibility;
1139 * Sets whether or not Windows compatibility is enabled.
1141 * @param bool $enhance
1143 * @return self The current Process instance
1145 public function setEnhanceWindowsCompatibility($enhance)
1147 $this->enhanceWindowsCompatibility = (bool) $enhance;
1153 * Returns whether sigchild compatibility mode is activated or not.
1157 public function getEnhanceSigchildCompatibility()
1159 return $this->enhanceSigchildCompatibility;
1163 * Activates sigchild compatibility mode.
1165 * Sigchild compatibility mode is required to get the exit code and
1166 * determine the success of a process when PHP has been compiled with
1167 * the --enable-sigchild option
1169 * @param bool $enhance
1171 * @return self The current Process instance
1173 public function setEnhanceSigchildCompatibility($enhance)
1175 $this->enhanceSigchildCompatibility = (bool) $enhance;
1181 * Performs a check between the timeout definition and the time the process started.
1183 * In case you run a background process (with the start method), you should
1184 * trigger this method regularly to ensure the process timeout
1186 * @throws ProcessTimedOutException In case the timeout was reached
1188 public function checkTimeout()
1190 if ($this->status !== self::STATUS_STARTED) {
1194 if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
1197 throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
1200 if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
1203 throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
1208 * Returns whether PTY is supported on the current operating system.
1212 public static function isPtySupported()
1216 if (null !== $result) {
1220 if ('\\' === DIRECTORY_SEPARATOR) {
1221 return $result = false;
1224 return $result = (bool) @proc_open('echo 1 >/dev/null', array(array('pty'), array('pty'), array('pty')), $pipes);
1228 * Creates the descriptors needed by the proc_open.
1232 private function getDescriptors()
1234 if ('\\' === DIRECTORY_SEPARATOR) {
1235 $this->processPipes = WindowsPipes::create($this, $this->input);
1237 $this->processPipes = UnixPipes::create($this, $this->input);
1240 return $this->processPipes->getDescriptors();
1244 * Builds up the callback used by wait().
1246 * The callbacks adds all occurred output to the specific buffer and calls
1247 * the user callback (if present) with the received output.
1249 * @param callable|null $callback The user defined PHP callback
1251 * @return \Closure A PHP closure
1253 protected function buildCallback($callback)
1257 $callback = function ($type, $data) use ($that, $callback, $out) {
1258 if ($out == $type) {
1259 $that->addOutput($data);
1261 $that->addErrorOutput($data);
1264 if (null !== $callback) {
1265 call_user_func($callback, $type, $data);
1273 * Updates the status of the process, reads pipes.
1275 * @param bool $blocking Whether to use a blocking read call
1277 protected function updateStatus($blocking)
1279 if (self::STATUS_STARTED !== $this->status) {
1283 $this->processInformation = proc_get_status($this->process);
1284 $running = $this->processInformation['running'];
1286 $this->readPipes($running && $blocking, '\\' !== DIRECTORY_SEPARATOR || !$running);
1288 if ($this->fallbackStatus && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
1289 $this->processInformation = $this->fallbackStatus + $this->processInformation;
1298 * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
1302 protected function isSigchildEnabled()
1304 if (null !== self::$sigchild) {
1305 return self::$sigchild;
1308 if (!function_exists('phpinfo') || defined('HHVM_VERSION')) {
1309 return self::$sigchild = false;
1313 phpinfo(INFO_GENERAL);
1315 return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
1319 * Reads pipes for the freshest output.
1321 * @param $caller The name of the method that needs fresh outputs
1323 * @throws LogicException in case output has been disabled or process is not started
1325 private function readPipesForOutput($caller)
1327 if ($this->outputDisabled) {
1328 throw new LogicException('Output has been disabled.');
1331 $this->requireProcessIsStarted($caller);
1333 $this->updateStatus(false);
1337 * Validates and returns the filtered timeout.
1339 * @param int|float|null $timeout
1341 * @return float|null
1343 * @throws InvalidArgumentException if the given timeout is a negative number
1345 private function validateTimeout($timeout)
1347 $timeout = (float) $timeout;
1349 if (0.0 === $timeout) {
1351 } elseif ($timeout < 0) {
1352 throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
1359 * Reads pipes, executes callback.
1361 * @param bool $blocking Whether to use blocking calls or not
1362 * @param bool $close Whether to close file handles or not
1364 private function readPipes($blocking, $close)
1366 $result = $this->processPipes->readAndWrite($blocking, $close);
1368 $callback = $this->callback;
1369 foreach ($result as $type => $data) {
1371 $callback($type === self::STDOUT ? self::OUT : self::ERR, $data);
1372 } elseif (!isset($this->fallbackStatus['signaled'])) {
1373 $this->fallbackStatus['exitcode'] = (int) $data;
1379 * Closes process resource, closes file handles, sets the exitcode.
1381 * @return int The exitcode
1383 private function close()
1385 $this->processPipes->close();
1386 if (is_resource($this->process)) {
1387 proc_close($this->process);
1389 $this->exitcode = $this->processInformation['exitcode'];
1390 $this->status = self::STATUS_TERMINATED;
1392 if (-1 === $this->exitcode) {
1393 if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
1394 // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
1395 $this->exitcode = 128 + $this->processInformation['termsig'];
1396 } elseif ($this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
1397 $this->processInformation['signaled'] = true;
1398 $this->processInformation['termsig'] = -1;
1402 // Free memory from self-reference callback created by buildCallback
1403 // Doing so in other contexts like __destruct or by garbage collector is ineffective
1404 // Now pipes are closed, so the callback is no longer necessary
1405 $this->callback = null;
1407 return $this->exitcode;
1411 * Resets data related to the latest run of the process.
1413 private function resetProcessData()
1415 $this->starttime = null;
1416 $this->callback = null;
1417 $this->exitcode = null;
1418 $this->fallbackStatus = array();
1419 $this->processInformation = null;
1420 $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
1421 $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
1422 $this->process = null;
1423 $this->latestSignal = null;
1424 $this->status = self::STATUS_READY;
1425 $this->incrementalOutputOffset = 0;
1426 $this->incrementalErrorOutputOffset = 0;
1430 * Sends a POSIX signal to the process.
1432 * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
1433 * @param bool $throwException Whether to throw exception in case signal failed
1435 * @return bool True if the signal was sent successfully, false otherwise
1437 * @throws LogicException In case the process is not running
1438 * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
1439 * @throws RuntimeException In case of failure
1441 private function doSignal($signal, $throwException)
1443 if (null === $pid = $this->getPid()) {
1444 if ($throwException) {
1445 throw new LogicException('Can not send signal on a non running process.');
1451 if ('\\' === DIRECTORY_SEPARATOR) {
1452 exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
1453 if ($exitCode && $this->isRunning()) {
1454 if ($throwException) {
1455 throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output)));
1461 if (!$this->enhanceSigchildCompatibility || !$this->isSigchildEnabled()) {
1462 $ok = @proc_terminate($this->process, $signal);
1463 } elseif (function_exists('posix_kill')) {
1464 $ok = @posix_kill($pid, $signal);
1465 } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), array(2 => array('pipe', 'w')), $pipes)) {
1466 $ok = false === fgets($pipes[2]);
1469 if ($throwException) {
1470 throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
1477 $this->latestSignal = (int) $signal;
1478 $this->fallbackStatus['signaled'] = true;
1479 $this->fallbackStatus['exitcode'] = -1;
1480 $this->fallbackStatus['termsig'] = $this->latestSignal;
1486 * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
1488 * @param string $functionName The function name that was called
1490 * @throws LogicException If the process has not run.
1492 private function requireProcessIsStarted($functionName)
1494 if (!$this->isStarted()) {
1495 throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
1500 * Ensures the process is terminated, throws a LogicException if the process has a status different than `terminated`.
1502 * @param string $functionName The function name that was called
1504 * @throws LogicException If the process is not yet terminated.
1506 private function requireProcessIsTerminated($functionName)
1508 if (!$this->isTerminated()) {
1509 throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));