Copied!

Process is a thin wrapper around proc_* functions to easily
start independent PHP processes.

CloneableInstantiableIterable
Constants
public Symfony\Component\Process\Process::ERR = 'err'
public Symfony\Component\Process\Process::ITER_KEEP_OUTPUT = 2
public Symfony\Component\Process\Process::ITER_NON_BLOCKING = 1
public Symfony\Component\Process\Process::ITER_SKIP_ERR = 8
public Symfony\Component\Process\Process::ITER_SKIP_OUT = 4
public Symfony\Component\Process\Process::OUT = 'out'
public Symfony\Component\Process\Process::STATUS_READY = 'ready'
public Symfony\Component\Process\Process::STATUS_STARTED = 'started'
public Symfony\Component\Process\Process::STATUS_TERMINATED = 'terminated'
public Symfony\Component\Process\Process::STDERR = 2
public Symfony\Component\Process\Process::STDIN = 0
public Symfony\Component\Process\Process::STDOUT = 1
public Symfony\Component\Process\Process::TIMEOUT_PRECISION = 0.2
Properties
public static $exitCodes = ['OK', 'General error', 'Misuse of shell builtins', 126 => 'Invoked command cannot execute', 127 => 'Command not found', 128 => 'Invalid exit argument', 129 => 'Hangup', 130 => 'Interrupt', 131 => 'Quit and dump core', 132 => 'Illegal instruction', 133 => 'Trace/breakpoint trap', 134 => 'Process aborted', 135 => 'Bus error: "access to undefined portion of memory object"', 136 => 'Floating point exception: "erroneous arithmetic operation"', 137 => 'Kill (terminate immediately)', 138 => 'User-defined 1', 139 => 'Segmentation violation', 140 => 'User-defined 2', 141 => 'Write to pipe with no one reading', 142 => 'Signal raised by alarm', 143 => 'Termination (request to terminate)', 145 => 'Child process terminated, stopped (or continued*)', 146 => 'Continue if stopped', 147 => 'Stop executing temporarily', 148 => 'Terminal stop signal', 149 => 'Background process attempting to read from tty ("in")', 150 => 'Background process attempting to write to tty ("out")', 151 => 'Urgent data available on socket', 152 => 'CPU time limit exceeded', 153 => 'File size limit exceeded', 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"', 155 => 'Profiling timer expired', 157 => 'Pollable event', 159 => 'Bad syscall']
 

Exit codes translation table.

User-defined errors must use exit codes in the 64-113 range.

Methods
public __clone()
public __construct(array $command, ?string $cwd = NULL, ?array $env = NULL, ?mixed $input = NULL, ?float $timeout = 60)
 
  • param array $command The command to run and its arguments listed as separate entries
  • param string|null $cwd The working directory or null to use the working dir of the current PHP process
  • param array|null $env The environment variables or null to use the same environment as the current PHP process
  • param mixed $input The input as stream resource, scalar or \Traversable, or null for no input
  • param int|float|null $timeout The timeout in seconds or null to disable
  • throws \LogicException When proc_open is not installed
public __destruct()
public __sleep() : array
public __wakeup()
public addErrorOutput(string $line) : void
 

Adds a line to the STDERR stream.

  • internal
public addOutput(string $line) : void
 

Adds a line to the STDOUT stream.

  • internal
public checkTimeout()
 

Performs a check between the timeout definition and the time the process started.

In case you run a background process (with the start method), you should
trigger this method regularly to ensure the process timeout

  • return void
  • throws \ProcessTimedOutException In case the timeout was reached
public clearErrorOutput() : static
 

Clears the process output.

  • return $this
public clearOutput() : static
 

Clears the process output.

  • return $this
public disableOutput() : static
 

Disables fetching output and error output from the underlying process.

  • return $this
  • throws \RuntimeException In case the process is already running
  • throws \LogicException if an idle timeout is set
public enableOutput() : static
 

Enables fetching output and error output from the underlying process.

  • return $this
  • throws \RuntimeException In case the process is already running
public static fromShellCommandline(string $command, ?string $cwd = NULL, ?array $env = NULL, ?mixed $input = NULL, ?float $timeout = 60) : static
 

Creates a Process instance as a command-line to be run in a shell wrapper.

Command-lines are parsed by the shell of your OS (/bin/sh on Unix-like, cmd.exe on Windows.)
This allows using e.g. pipes or conditional execution. In this mode, signals are sent to the
shell wrapper and not to your commands.

In order to inject dynamic values into command-lines, we strongly recommend using placeholders.
This will save escaping values, which is not portable nor secure anyway:

$process = Process::fromShellCommandline('my_command "${:MY_VAR}"');
$process->run(null, ['MY_VAR' => $theValue]);

  • param string $command The command line to pass to the shell of the OS
  • param string|null $cwd The working directory or null to use the working dir of the current PHP process
  • param array|null $env The environment variables or null to use the same environment as the current PHP process
  • param mixed $input The input as stream resource, scalar or \Traversable, or null for no input
  • param int|float|null $timeout The timeout in seconds or null to disable
  • throws \LogicException When proc_open is not installed
public getCommandLine() : string
 

Gets the command line to be executed.

public getEnv() : array
 

Gets the environment variables.

public getErrorOutput() : string
 

Returns the current error output of the process (STDERR).

  • throws \LogicException in case the output has been disabled
  • throws \LogicException In case the process is not started
public getExitCode() : ?int
 

Returns the exit code returned by the process.

  • return int|null The exit status code, null if the Process is not terminated
public getExitCodeText() : ?string
 

Returns a string representation for the exit code returned by the process.

This method relies on the Unix exit code status standardization
and might not be relevant for other operating systems.

  • return string|null A string representation for the exit status code, null if the Process is not terminated
  • see http://tldp.org/LDP/abs/html/exitcodes.html
  • see http://en.wikipedia.org/wiki/Unix_signal
public getIdleTimeout() : ?float
 

Gets the process idle timeout in seconds (max. time since last output).

public getIncrementalErrorOutput() : string
 

Returns the errorOutput incrementally.

In comparison with the getErrorOutput method which always return the
whole error output, this one returns the new error output since the last
call.

  • throws \LogicException in case the output has been disabled
  • throws \LogicException In case the process is not started
public getIncrementalOutput() : string
 

Returns the output incrementally.

In comparison with the getOutput method which always return the whole
output, this one returns the new output since the last call.

  • throws \LogicException in case the output has been disabled
  • throws \LogicException In case the process is not started
public getInput()
 

Gets the Process input.

  • return resource|string|\Iterator|null
public getIterator(int $flags = 0) : Generator
 

Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR).

  • param int $flags A bit field of Process::ITER_* flags
  • return \Generator<string,string>
  • throws \LogicException in case the output has been disabled
  • throws \LogicException In case the process is not started
public getLastOutputTime() : ?float
 

Gets the last output time in seconds.

public getOutput() : string
 

Returns the current output of the process (STDOUT).

  • throws \LogicException in case the output has been disabled
  • throws \LogicException In case the process is not started
public getPid() : ?int
 

Returns the Pid (process identifier), if applicable.

  • return int|null The process id if running, null otherwise
public getStartTime() : float
 
  • throws \LogicException in case process is not started
public getStatus() : string
 

Gets the process status.

The status is one of: ready, started, terminated.

public getStopSignal() : int
 

Returns the number of the signal that caused the child process to stop its execution.

It is only meaningful if hasBeenStopped() returns true.

  • throws \LogicException In case the process is not terminated
public getTermSignal() : int
 

Returns the number of the signal that caused the child process to terminate its execution.

It is only meaningful if hasBeenSignaled() returns true.

  • throws \RuntimeException In case --enable-sigchild is activated
  • throws \LogicException In case the process is not terminated
public getTimeout() : ?float
 

Gets the process timeout in seconds (max. runtime).

public getWorkingDirectory() : ?string
 

Gets the working directory.

public hasBeenSignaled() : bool
 

Returns true if the child process has been terminated by an uncaught signal.

It always returns false on Windows.

  • throws \LogicException In case the process is not terminated
public hasBeenStopped() : bool
 

Returns true if the child process has been stopped by a signal.

It always returns false on Windows.

  • throws \LogicException In case the process is not terminated
public isOutputDisabled() : bool
 

Returns true in case the output is disabled, false otherwise.

public isPty() : bool
 

Returns PTY state.

public static isPtySupported() : bool
 

Returns whether PTY is supported on the current operating system.

public isRunning() : bool
 

Checks if the process is currently running.

public isStarted() : bool
 

Checks if the process has been started with no regard to the current state.

public isSuccessful() : bool
 

Checks if the process ended successfully.

public isTerminated() : bool
 

Checks if the process is terminated.

public isTty() : bool
 

Checks if the TTY mode is enabled.

public static isTtySupported() : bool
 

Returns whether TTY is supported on the current operating system.

public mustRun(?callable $callback = NULL, array $env = []) : static
 

Runs the process.

This is identical to run() except that an exception is thrown if the process
exits with a non-zero exit code.

  • return $this
  • throws \ProcessFailedException if the process didn't terminate successfully
  • final
public restart(?callable $callback = NULL, array $env = []) : static
 

Restarts the process.

Be warned that the process is cloned before being started.

  • param callable|null $callback A PHP callback to run whenever there is some
    output available on STDOUT or STDERR
  • throws \RuntimeException When process can't be launched
  • throws \RuntimeException When process is already running
  • see \start()
  • final
public run(?callable $callback = NULL, array $env = []) : int
 

Runs the process.

The callback receives the type of output (out or err) and
some bytes from the output in real-time. It allows to have feedback
from the independent process during execution.

The STDOUT and STDERR are also available after the process is finished
via the getOutput() and getErrorOutput() methods.

  • param callable|null $callback A PHP callback to run whenever there is some
    output available on STDOUT or STDERR
  • return int The exit status code
  • throws \RuntimeException When process can't be launched
  • throws \RuntimeException When process is already running
  • throws \ProcessTimedOutException When process timed out
  • throws \ProcessSignaledException When process stopped after receiving signal
  • throws \LogicException In case a callback is provided and output has been disabled
  • final
public setEnv(array $env) : static
 

Sets the environment variables.

  • param (string|\Stringable)[] $env The new environment variables
  • return $this
public setIdleTimeout(?float $timeout) : static
 

Sets the process idle timeout (max. time since last output) in seconds.

To disable the timeout, set this value to null.

  • return $this
  • throws \LogicException if the output is disabled
  • throws \InvalidArgumentException if the timeout is negative
public setInput(?mixed $input) : static
 

Sets the input.

This content will be passed to the underlying process standard input.

  • param string|int|float|bool|resource|\Traversable|null $input The content
  • return $this
  • throws \LogicException In case the process is running
public setOptions(array $options)
 

Defines options to pass to the underlying proc_open().

  • see https://php.net/proc_openfor the options supported by PHP.

    Enabling the "create_new_console" option allows a subprocess to continue
    to run after the main process exited, on both Windows and *nix
  • return void
public setPty(bool $bool) : static
 

Sets PTY mode.

  • return $this
public setTimeout(?float $timeout) : static
 

Sets the process timeout (max. runtime) in seconds.

To disable the timeout, set this value to null.

  • return $this
  • throws \InvalidArgumentException if the timeout is negative
public setTty(bool $tty) : static
 

Enables or disables the TTY mode.

  • return $this
  • throws \RuntimeException In case the TTY mode is not supported
public setWorkingDirectory(string $cwd) : static
 

Sets the current working directory.

  • return $this
public signal(int $signal) : static
 

Sends a POSIX signal to the process.

  • param int $signal A valid POSIX signal (see https://php.net/pcntl.constants)
  • return $this
  • throws \LogicException In case the process is not running
  • throws \RuntimeException In case --enable-sigchild is activated and the process can't be killed
  • throws \RuntimeException In case of failure
public start(?callable $callback = NULL, array $env = [])
 

Starts the process and returns after writing the input to STDIN.

This method blocks until all STDIN data is sent to the process then it
returns while the process runs in the background.

The termination of the process can be awaited with wait().

The callback receives the type of output (out or err) and some bytes from
the output in real-time while writing the standard input to the process.
It allows to have feedback from the independent process during execution.

  • param callable|null $callback A PHP callback to run whenever there is some
    output available on STDOUT or STDERR
  • return void
  • throws \RuntimeException When process can't be launched
  • throws \RuntimeException When process is already running
  • throws \LogicException In case a callback is provided and output has been disabled
public stop(float $timeout = 10, ?int $signal = NULL) : ?int
 

Stops the process.

  • param int|float $timeout The timeout in seconds
  • param int|null $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9)
  • return int|null The exit-code of the process or null if it's not running
public wait(?callable $callback = NULL) : int
 

Waits for the process to terminate.

The callback receives the type of output (out or err) and some bytes
from the output in real-time while writing the standard input to the process.
It allows to have feedback from the independent process during execution.

  • param callable|null $callback A valid PHP callback
  • return int The exitcode of the process
  • throws \ProcessTimedOutException When process timed out
  • throws \ProcessSignaledException When process stopped after receiving signal
  • throws \LogicException When process is not yet started
public waitUntil(callable $callback) : bool
 

Waits until the callback returns true.

The callback receives the type of output (out or err) and some bytes
from the output in real-time while writing the standard input to the process.
It allows to have feedback from the independent process during execution.

  • throws \RuntimeException When process timed out
  • throws \LogicException When process is not yet started
  • throws \ProcessTimedOutException In case the timeout was reached
Methods
protected buildCallback(?callable $callback = NULL) : Closure
 

Builds up the callback used by wait().

The callbacks adds all occurred output to the specific buffer and calls
the user callback (if present) with the received output.

  • param callable|null $callback The user defined PHP callback
protected isSigchildEnabled() : bool
 

Returns whether PHP has been compiled with the '--enable-sigchild' option or not.

protected updateStatus(bool $blocking)
 

Updates the status of the process, reads pipes.

  • param bool $blocking Whether to use a blocking read call
  • return void
Properties
private $callback = NULL
private $commandline = NULL
private $cwd = NULL
private $env = []
private $exitcode = NULL
private $fallbackStatus = []
private $hasCallback = false
private $idleTimeout = NULL
private $incrementalErrorOutputOffset = 0
private $incrementalOutputOffset = 0
private $input = NULL
private $lastOutputTime = NULL
private $latestSignal = NULL
private $options = ['suppress_errors' => true, 'bypass_shell' => true]
private $outputDisabled = false
private $process = NULL
private $processInformation = NULL
private $processPipes = NULL
 
  • var \PipesInterface
private $pty = NULL
private static $sigchild = NULL
private $starttime = NULL
private $status = 'ready'
private $stderr = NULL
private $stdout = NULL
private $timeout = NULL
private $tty = false
private $useFileHandles = false
Methods
private close() : int
 

Closes process resource, closes file handles, sets the exitcode.

  • return int The exitcode
private doSignal(int $signal, bool $throwException) : bool
 

Sends a POSIX signal to the process.

  • param int $signal A valid POSIX signal (see https://php.net/pcntl.constants)
  • param bool $throwException Whether to throw exception in case signal failed
  • throws \LogicException In case the process is not running
  • throws \RuntimeException In case --enable-sigchild is activated and the process can't be killed
  • throws \RuntimeException In case of failure
private escapeArgument(?string $argument) : string
 

Escapes a string to be used as a shell argument.

private getDefaultEnv() : array
private getDescriptors() : array
 

Creates the descriptors needed by the proc_open.

private prepareWindowsCommandLine(string $cmd, array $env) : string
private readPipes(bool $blocking, bool $close) : void
 

Reads pipes, executes callback.

  • param bool $blocking Whether to use blocking calls or not
  • param bool $close Whether to close file handles or not
private readPipesForOutput(string $caller, bool $blocking = false) : void
 

Reads pipes for the freshest output.

  • param string $caller The name of the method that needs fresh outputs
  • param bool $blocking Whether to use blocking calls or not
  • throws \LogicException in case output has been disabled or process is not started
private replacePlaceholders(string $commandline, array $env) : string
private requireProcessIsStarted(string $functionName) : void
 

Ensures the process is running or terminated, throws a LogicException if the process has a not started.

  • throws \LogicException if the process has not run
private requireProcessIsTerminated(string $functionName) : void
 

Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".

  • throws \LogicException if the process is not yet terminated
private resetProcessData() : void
 

Resets data related to the latest run of the process.

private validateTimeout(?float $timeout) : ?float
 

Validates and returns the filtered timeout.

  • throws \InvalidArgumentException if the given timeout is a negative number
Properties
public static $exitCodes = ['OK', 'General error', 'Misuse of shell builtins', 126 => 'Invoked command cannot execute', 127 => 'Command not found', 128 => 'Invalid exit argument', 129 => 'Hangup', 130 => 'Interrupt', 131 => 'Quit and dump core', 132 => 'Illegal instruction', 133 => 'Trace/breakpoint trap', 134 => 'Process aborted', 135 => 'Bus error: "access to undefined portion of memory object"', 136 => 'Floating point exception: "erroneous arithmetic operation"', 137 => 'Kill (terminate immediately)', 138 => 'User-defined 1', 139 => 'Segmentation violation', 140 => 'User-defined 2', 141 => 'Write to pipe with no one reading', 142 => 'Signal raised by alarm', 143 => 'Termination (request to terminate)', 145 => 'Child process terminated, stopped (or continued*)', 146 => 'Continue if stopped', 147 => 'Stop executing temporarily', 148 => 'Terminal stop signal', 149 => 'Background process attempting to read from tty ("in")', 150 => 'Background process attempting to write to tty ("out")', 151 => 'Urgent data available on socket', 152 => 'CPU time limit exceeded', 153 => 'File size limit exceeded', 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"', 155 => 'Profiling timer expired', 157 => 'Pollable event', 159 => 'Bad syscall']
 

Exit codes translation table.

User-defined errors must use exit codes in the 64-113 range.

private static $sigchild = NULL
Methods
public static fromShellCommandline(string $command, ?string $cwd = NULL, ?array $env = NULL, ?mixed $input = NULL, ?float $timeout = 60) : static
 

Creates a Process instance as a command-line to be run in a shell wrapper.

Command-lines are parsed by the shell of your OS (/bin/sh on Unix-like, cmd.exe on Windows.)
This allows using e.g. pipes or conditional execution. In this mode, signals are sent to the
shell wrapper and not to your commands.

In order to inject dynamic values into command-lines, we strongly recommend using placeholders.
This will save escaping values, which is not portable nor secure anyway:

$process = Process::fromShellCommandline('my_command "${:MY_VAR}"');
$process->run(null, ['MY_VAR' => $theValue]);

  • param string $command The command line to pass to the shell of the OS
  • param string|null $cwd The working directory or null to use the working dir of the current PHP process
  • param array|null $env The environment variables or null to use the same environment as the current PHP process
  • param mixed $input The input as stream resource, scalar or \Traversable, or null for no input
  • param int|float|null $timeout The timeout in seconds or null to disable
  • throws \LogicException When proc_open is not installed
public static isPtySupported() : bool
 

Returns whether PTY is supported on the current operating system.

public static isTtySupported() : bool
 

Returns whether TTY is supported on the current operating system.

© 2023 Bruce Wells
Search Namespaces \ Classes
Configuration