Process
in package
implements
IteratorAggregate
Process is a thin wrapper around proc_* functions to easily start independent PHP processes.
Tags
Table of Contents
Interfaces
- IteratorAggregate
Constants
- ERR = 'err'
- ITER_KEEP_OUTPUT = 2
- ITER_NON_BLOCKING = 1
- ITER_SKIP_ERR = 8
- ITER_SKIP_OUT = 4
- OUT = 'out'
- STATUS_READY = 'ready'
- STATUS_STARTED = 'started'
- STATUS_TERMINATED = 'terminated'
- STDERR = 2
- STDIN = 0
- STDOUT = 1
- TIMEOUT_PRECISION = 0.2
Properties
- $exitCodes : mixed
- Exit codes translation table.
- $cachedExitCode : int|null
- $callback : Closure|null
- $commandline : array<string|int, mixed>|string
- $cwd : string|null
- $env : array<string|int, mixed>
- $exitcode : int|null
- $fallbackStatus : array<string|int, mixed>
- $idleTimeout : float|null
- $incrementalErrorOutputOffset : int
- $incrementalOutputOffset : int
- $input : resource|string|Iterator|null
- $lastOutputTime : float|null
- $latestSignal : int|null
- $options : array<string|int, mixed>
- $outputDisabled : bool
- $process : resource|null
- $processInformation : array<string|int, mixed>
- $processPipes : WindowsPipes|UnixPipes
- $pty : bool
- $sigchild : bool|null
- $starttime : float|null
- $status : string
- $stderr : resource
- $stdout : resource
- $timeout : float|null
- $tty : bool
Methods
- __clone() : mixed
- __construct() : mixed
- __destruct() : mixed
- __sleep() : array<string|int, mixed>
- __wakeup() : void
- checkTimeout() : void
- Performs a check between the timeout definition and the time the process started.
- clearErrorOutput() : $this
- Clears the process output.
- clearOutput() : $this
- Clears the process output.
- disableOutput() : $this
- Disables fetching output and error output from the underlying process.
- enableOutput() : $this
- Enables fetching output and error output from the underlying process.
- fromShellCommandline() : static
- Creates a Process instance as a command-line to be run in a shell wrapper.
- getCommandLine() : string
- Gets the command line to be executed.
- getEnv() : array<string|int, mixed>
- Gets the environment variables.
- getErrorOutput() : string
- Returns the current error output of the process (STDERR).
- getExitCode() : int|null
- Returns the exit code returned by the process.
- getExitCodeText() : string|null
- Returns a string representation for the exit code returned by the process.
- getIdleTimeout() : float|null
- Gets the process idle timeout in seconds (max. time since last output).
- getIncrementalErrorOutput() : string
- Returns the errorOutput incrementally.
- getIncrementalOutput() : string
- Returns the output incrementally.
- getInput() : resource|string|Iterator|null
- Gets the Process input.
- getIterator() : Generator<string, string>
- Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR).
- getLastOutputTime() : float|null
- Gets the last output time in seconds.
- getOutput() : string
- Returns the current output of the process (STDOUT).
- getPid() : int|null
- Returns the Pid (process identifier), if applicable.
- getStartTime() : float
- getStatus() : string
- Gets the process status.
- getStopSignal() : int
- Returns the number of the signal that caused the child process to stop its execution.
- getTermSignal() : int
- Returns the number of the signal that caused the child process to terminate its execution.
- getTimeout() : float|null
- Gets the process timeout in seconds (max. runtime).
- getWorkingDirectory() : string|null
- Gets the working directory.
- hasBeenSignaled() : bool
- Returns true if the child process has been terminated by an uncaught signal.
- hasBeenStopped() : bool
- Returns true if the child process has been stopped by a signal.
- isOutputDisabled() : bool
- Returns true in case the output is disabled, false otherwise.
- isPty() : bool
- Returns PTY state.
- isPtySupported() : bool
- Returns whether PTY is supported on the current operating system.
- isRunning() : bool
- Checks if the process is currently running.
- isStarted() : bool
- Checks if the process has been started with no regard to the current state.
- isSuccessful() : bool
- Checks if the process ended successfully.
- isTerminated() : bool
- Checks if the process is terminated.
- isTty() : bool
- Checks if the TTY mode is enabled.
- isTtySupported() : bool
- Returns whether TTY is supported on the current operating system.
- mustRun() : $this
- Runs the process.
- restart() : static
- Restarts the process.
- run() : int
- Runs the process.
- setEnv() : $this
- Sets the environment variables.
- setIdleTimeout() : $this
- Sets the process idle timeout (max. time since last output) in seconds.
- setInput() : $this
- Sets the input.
- setOptions() : void
- Defines options to pass to the underlying proc_open().
- setPty() : $this
- Sets PTY mode.
- setTimeout() : $this
- Sets the process timeout (max. runtime) in seconds.
- setTty() : $this
- Enables or disables the TTY mode.
- setWorkingDirectory() : $this
- Sets the current working directory.
- signal() : $this
- Sends a POSIX signal to the process.
- start() : void
- Starts the process and returns after writing the input to STDIN.
- stop() : int|null
- Stops the process.
- wait() : int
- Waits for the process to terminate.
- waitUntil() : bool
- Waits until the callback returns true.
- buildCallback() : Closure
- Builds up the callback used by wait().
- isSigchildEnabled() : bool
- Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
- updateStatus() : void
- Updates the status of the process, reads pipes.
- close() : int
- Closes process resource, closes file handles, sets the exitcode.
- doSignal() : bool
- Sends a POSIX signal to the process.
- escapeArgument() : string
- Escapes a string to be used as a shell argument.
- getDefaultEnv() : array<string|int, mixed>
- getDescriptors() : array<string|int, mixed>
- Creates the descriptors needed by the proc_open.
- prepareWindowsCommandLine() : string
- readPipes() : void
- Reads pipes, executes callback.
- readPipesForOutput() : void
- Reads pipes for the freshest output.
- replacePlaceholders() : string
- requireProcessIsStarted() : void
- Ensures the process is running or terminated, throws a LogicException if the process has a not started.
- requireProcessIsTerminated() : void
- Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".
- resetProcessData() : void
- Resets data related to the latest run of the process.
- validateTimeout() : float|null
- Validates and returns the filtered timeout.
Constants
ERR
public
mixed
ERR
= 'err'
ITER_KEEP_OUTPUT
public
mixed
ITER_KEEP_OUTPUT
= 2
ITER_NON_BLOCKING
public
mixed
ITER_NON_BLOCKING
= 1
ITER_SKIP_ERR
public
mixed
ITER_SKIP_ERR
= 8
ITER_SKIP_OUT
public
mixed
ITER_SKIP_OUT
= 4
OUT
public
mixed
OUT
= 'out'
STATUS_READY
public
mixed
STATUS_READY
= 'ready'
STATUS_STARTED
public
mixed
STATUS_STARTED
= 'started'
STATUS_TERMINATED
public
mixed
STATUS_TERMINATED
= 'terminated'
STDERR
public
mixed
STDERR
= 2
STDIN
public
mixed
STDIN
= 0
STDOUT
public
mixed
STDOUT
= 1
TIMEOUT_PRECISION
public
mixed
TIMEOUT_PRECISION
= 0.2
Properties
$exitCodes
Exit codes translation table.
public
static mixed
$exitCodes
= [
0 => 'OK',
1 => 'General error',
2 => 'Misuse of shell builtins',
126 => 'Invoked command cannot execute',
127 => 'Command not found',
128 => 'Invalid exit argument',
// signals
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)',
// 144 - not defined
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',
// 156 - not defined
157 => 'Pollable event',
// 158 - not defined
159 => 'Bad syscall',
]
User-defined errors must use exit codes in the 64-113 range.
$cachedExitCode
private
int|null
$cachedExitCode
= null
$callback
private
Closure|null
$callback
= null
$commandline
private
array<string|int, mixed>|string
$commandline
$cwd
private
string|null
$cwd
$env
private
array<string|int, mixed>
$env
= []
$exitcode
private
int|null
$exitcode
= null
$fallbackStatus
private
array<string|int, mixed>
$fallbackStatus
= []
$idleTimeout
private
float|null
$idleTimeout
= null
$incrementalErrorOutputOffset
private
int
$incrementalErrorOutputOffset
= 0
$incrementalOutputOffset
private
int
$incrementalOutputOffset
= 0
$input
private
resource|string|Iterator|null
$input
$lastOutputTime
private
float|null
$lastOutputTime
= null
$latestSignal
private
int|null
$latestSignal
= null
$options
private
array<string|int, mixed>
$options
= ['suppress_errors' => true, 'bypass_shell' => true]
$outputDisabled
private
bool
$outputDisabled
= false
$process
private
resource|null
$process
$processInformation
private
array<string|int, mixed>
$processInformation
$processPipes
private
WindowsPipes|UnixPipes
$processPipes
$pty
private
bool
$pty
$sigchild
private
static bool|null
$sigchild
= null
$starttime
private
float|null
$starttime
= null
$status
private
string
$status
= self::STATUS_READY
$stderr
private
resource
$stderr
$stdout
private
resource
$stdout
$timeout
private
float|null
$timeout
= null
$tty
private
bool
$tty
= false
Methods
__clone()
public
__clone() : mixed
__construct()
public
__construct(array<string|int, mixed> $command[, string|null $cwd = null ][, array<string|int, mixed>|null $env = null ][, mixed $input = null ][, int|float|null $timeout = 60 ]) : mixed
Parameters
- $command : array<string|int, mixed>
-
The command to run and its arguments listed as separate entries
- $cwd : string|null = null
-
The working directory or null to use the working dir of the current PHP process
- $env : array<string|int, mixed>|null = null
-
The environment variables or null to use the same environment as the current PHP process
- $input : mixed = null
-
The input as stream resource, scalar or \Traversable, or null for no input
- $timeout : int|float|null = 60
-
The timeout in seconds or null to disable
Tags
__destruct()
public
__destruct() : mixed
__sleep()
public
__sleep() : array<string|int, mixed>
Return values
array<string|int, mixed>__wakeup()
public
__wakeup() : void
checkTimeout()
Performs a check between the timeout definition and the time the process started.
public
checkTimeout() : void
In case you run a background process (with the start method), you should trigger this method regularly to ensure the process timeout
Tags
clearErrorOutput()
Clears the process output.
public
clearErrorOutput() : $this
Return values
$thisclearOutput()
Clears the process output.
public
clearOutput() : $this
Return values
$thisdisableOutput()
Disables fetching output and error output from the underlying process.
public
disableOutput() : $this
Tags
Return values
$thisenableOutput()
Enables fetching output and error output from the underlying process.
public
enableOutput() : $this
Tags
Return values
$thisfromShellCommandline()
Creates a Process instance as a command-line to be run in a shell wrapper.
public
static fromShellCommandline(string $command[, string|null $cwd = null ][, array<string|int, mixed>|null $env = null ][, mixed $input = null ][, int|float|null $timeout = 60 ]) : static
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]);
Parameters
- $command : string
-
The command line to pass to the shell of the OS
- $cwd : string|null = null
-
The working directory or null to use the working dir of the current PHP process
- $env : array<string|int, mixed>|null = null
-
The environment variables or null to use the same environment as the current PHP process
- $input : mixed = null
-
The input as stream resource, scalar or \Traversable, or null for no input
- $timeout : int|float|null = 60
-
The timeout in seconds or null to disable
Tags
Return values
staticgetCommandLine()
Gets the command line to be executed.
public
getCommandLine() : string
Return values
stringgetEnv()
Gets the environment variables.
public
getEnv() : array<string|int, mixed>
Return values
array<string|int, mixed>getErrorOutput()
Returns the current error output of the process (STDERR).
public
getErrorOutput() : string
Tags
Return values
stringgetExitCode()
Returns the exit code returned by the process.
public
getExitCode() : int|null
Return values
int|null —The exit status code, null if the Process is not terminated
getExitCodeText()
Returns a string representation for the exit code returned by the process.
public
getExitCodeText() : string|null
This method relies on the Unix exit code status standardization and might not be relevant for other operating systems.
Tags
Return values
string|null —A string representation for the exit status code, null if the Process is not terminated
getIdleTimeout()
Gets the process idle timeout in seconds (max. time since last output).
public
getIdleTimeout() : float|null
Return values
float|nullgetIncrementalErrorOutput()
Returns the errorOutput incrementally.
public
getIncrementalErrorOutput() : string
In comparison with the getErrorOutput method which always return the whole error output, this one returns the new error output since the last call.
Tags
Return values
stringgetIncrementalOutput()
Returns the output incrementally.
public
getIncrementalOutput() : string
In comparison with the getOutput method which always return the whole output, this one returns the new output since the last call.
Tags
Return values
stringgetInput()
Gets the Process input.
public
getInput() : resource|string|Iterator|null
Return values
resource|string|Iterator|nullgetIterator()
Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR).
public
getIterator([int $flags = 0 ]) : Generator<string, string>
Parameters
- $flags : int = 0
-
A bit field of Process::ITER_* flags
Tags
Return values
Generator<string, string>getLastOutputTime()
Gets the last output time in seconds.
public
getLastOutputTime() : float|null
Return values
float|nullgetOutput()
Returns the current output of the process (STDOUT).
public
getOutput() : string
Tags
Return values
stringgetPid()
Returns the Pid (process identifier), if applicable.
public
getPid() : int|null
Return values
int|null —The process id if running, null otherwise
getStartTime()
public
getStartTime() : float
Tags
Return values
floatgetStatus()
Gets the process status.
public
getStatus() : string
The status is one of: ready, started, terminated.
Return values
stringgetStopSignal()
Returns the number of the signal that caused the child process to stop its execution.
public
getStopSignal() : int
It is only meaningful if hasBeenStopped() returns true.
Tags
Return values
intgetTermSignal()
Returns the number of the signal that caused the child process to terminate its execution.
public
getTermSignal() : int
It is only meaningful if hasBeenSignaled() returns true.
Tags
Return values
intgetTimeout()
Gets the process timeout in seconds (max. runtime).
public
getTimeout() : float|null
Return values
float|nullgetWorkingDirectory()
Gets the working directory.
public
getWorkingDirectory() : string|null
Return values
string|nullhasBeenSignaled()
Returns true if the child process has been terminated by an uncaught signal.
public
hasBeenSignaled() : bool
It always returns false on Windows.
Tags
Return values
boolhasBeenStopped()
Returns true if the child process has been stopped by a signal.
public
hasBeenStopped() : bool
It always returns false on Windows.
Tags
Return values
boolisOutputDisabled()
Returns true in case the output is disabled, false otherwise.
public
isOutputDisabled() : bool
Return values
boolisPty()
Returns PTY state.
public
isPty() : bool
Return values
boolisPtySupported()
Returns whether PTY is supported on the current operating system.
public
static isPtySupported() : bool
Return values
boolisRunning()
Checks if the process is currently running.
public
isRunning() : bool
Return values
boolisStarted()
Checks if the process has been started with no regard to the current state.
public
isStarted() : bool
Return values
boolisSuccessful()
Checks if the process ended successfully.
public
isSuccessful() : bool
Return values
boolisTerminated()
Checks if the process is terminated.
public
isTerminated() : bool
Return values
boolisTty()
Checks if the TTY mode is enabled.
public
isTty() : bool
Return values
boolisTtySupported()
Returns whether TTY is supported on the current operating system.
public
static isTtySupported() : bool
Return values
boolmustRun()
Runs the process.
public
mustRun([callable|null $callback = null ][, array<string|int, mixed> $env = [] ]) : $this
This is identical to run() except that an exception is thrown if the process exits with a non-zero exit code.
Parameters
- $callback : callable|null = null
- $env : array<string|int, mixed> = []
Tags
Return values
$thisrestart()
Restarts the process.
public
restart([callable|null $callback = null ][, array<string|int, mixed> $env = [] ]) : static
Be warned that the process is cloned before being started.
Parameters
- $callback : callable|null = null
-
A PHP callback to run whenever there is some output available on STDOUT or STDERR
- $env : array<string|int, mixed> = []
Tags
Return values
staticrun()
Runs the process.
public
run([callable|null $callback = null ][, array<string|int, mixed> $env = [] ]) : int
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.
Parameters
- $callback : callable|null = null
-
A PHP callback to run whenever there is some output available on STDOUT or STDERR
- $env : array<string|int, mixed> = []
Tags
Return values
int —The exit status code
setEnv()
Sets the environment variables.
public
setEnv(array<string|int, string|Stringable> $env) : $this
Parameters
- $env : array<string|int, string|Stringable>
-
The new environment variables
Return values
$thissetIdleTimeout()
Sets the process idle timeout (max. time since last output) in seconds.
public
setIdleTimeout(float|null $timeout) : $this
To disable the timeout, set this value to null.
Parameters
- $timeout : float|null
Tags
Return values
$thissetInput()
Sets the input.
public
setInput(string|resource|Traversable|self|null $input) : $this
This content will be passed to the underlying process standard input.
Parameters
- $input : string|resource|Traversable|self|null
-
The content
Tags
Return values
$thissetOptions()
Defines options to pass to the underlying proc_open().
public
setOptions(array<string|int, mixed> $options) : void
Parameters
- $options : array<string|int, mixed>
Tags
setPty()
Sets PTY mode.
public
setPty(bool $bool) : $this
Parameters
- $bool : bool
Return values
$thissetTimeout()
Sets the process timeout (max. runtime) in seconds.
public
setTimeout(float|null $timeout) : $this
To disable the timeout, set this value to null.
Parameters
- $timeout : float|null
Tags
Return values
$thissetTty()
Enables or disables the TTY mode.
public
setTty(bool $tty) : $this
Parameters
- $tty : bool
Tags
Return values
$thissetWorkingDirectory()
Sets the current working directory.
public
setWorkingDirectory(string $cwd) : $this
Parameters
- $cwd : string
Return values
$thissignal()
Sends a POSIX signal to the process.
public
signal(int $signal) : $this
Parameters
- $signal : int
-
A valid POSIX signal (see https://php.net/pcntl.constants)
Tags
Return values
$thisstart()
Starts the process and returns after writing the input to STDIN.
public
start([callable|null $callback = null ][, array<string|int, mixed> $env = [] ]) : void
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.
Parameters
- $callback : callable|null = null
-
A PHP callback to run whenever there is some output available on STDOUT or STDERR
- $env : array<string|int, mixed> = []
Tags
stop()
Stops the process.
public
stop([int|float $timeout = 10 ][, int|null $signal = null ]) : int|null
Parameters
- $timeout : int|float = 10
-
The timeout in seconds
- $signal : int|null = null
-
A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9)
Return values
int|null —The exit-code of the process or null if it's not running
wait()
Waits for the process to terminate.
public
wait([callable|null $callback = null ]) : int
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.
Parameters
- $callback : callable|null = null
-
A valid PHP callback
Tags
Return values
int —The exitcode of the process
waitUntil()
Waits until the callback returns true.
public
waitUntil(callable $callback) : bool
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.
Parameters
- $callback : callable
Tags
Return values
boolbuildCallback()
Builds up the callback used by wait().
protected
buildCallback([callable|null $callback = null ]) : Closure
The callbacks adds all occurred output to the specific buffer and calls the user callback (if present) with the received output.
Parameters
- $callback : callable|null = null
-
The user defined PHP callback
Return values
ClosureisSigchildEnabled()
Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
protected
isSigchildEnabled() : bool
Return values
boolupdateStatus()
Updates the status of the process, reads pipes.
protected
updateStatus(bool $blocking) : void
Parameters
- $blocking : bool
-
Whether to use a blocking read call
close()
Closes process resource, closes file handles, sets the exitcode.
private
close() : int
Return values
int —The exitcode
doSignal()
Sends a POSIX signal to the process.
private
doSignal(int $signal, bool $throwException) : bool
Parameters
- $signal : int
-
A valid POSIX signal (see https://php.net/pcntl.constants)
- $throwException : bool
-
Whether to throw exception in case signal failed
Tags
Return values
boolescapeArgument()
Escapes a string to be used as a shell argument.
private
escapeArgument(string|null $argument) : string
Parameters
- $argument : string|null
Return values
stringgetDefaultEnv()
private
getDefaultEnv() : array<string|int, mixed>
Return values
array<string|int, mixed>getDescriptors()
Creates the descriptors needed by the proc_open.
private
getDescriptors(bool $hasCallback) : array<string|int, mixed>
Parameters
- $hasCallback : bool
Return values
array<string|int, mixed>prepareWindowsCommandLine()
private
prepareWindowsCommandLine(string $cmd, array<string|int, mixed> &$env) : string
Parameters
- $cmd : string
- $env : array<string|int, mixed>
Return values
stringreadPipes()
Reads pipes, executes callback.
private
readPipes(bool $blocking, bool $close) : void
Parameters
- $blocking : bool
-
Whether to use blocking calls or not
- $close : bool
-
Whether to close file handles or not
readPipesForOutput()
Reads pipes for the freshest output.
private
readPipesForOutput(string $caller[, bool $blocking = false ]) : void
Parameters
- $caller : string
-
The name of the method that needs fresh outputs
- $blocking : bool = false
-
Whether to use blocking calls or not
Tags
replacePlaceholders()
private
replacePlaceholders(string $commandline, array<string|int, mixed> $env) : string
Parameters
- $commandline : string
- $env : array<string|int, mixed>
Return values
stringrequireProcessIsStarted()
Ensures the process is running or terminated, throws a LogicException if the process has a not started.
private
requireProcessIsStarted(string $functionName) : void
Parameters
- $functionName : string
Tags
requireProcessIsTerminated()
Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".
private
requireProcessIsTerminated(string $functionName) : void
Parameters
- $functionName : string
Tags
resetProcessData()
Resets data related to the latest run of the process.
private
resetProcessData() : void
validateTimeout()
Validates and returns the filtered timeout.
private
validateTimeout(float|null $timeout) : float|null
Parameters
- $timeout : float|null