The Process Component

The Process component executes commands in sub-processes.

Installation

  1. $ composer require symfony/process

Note

If you install this component outside of a Symfony application, you mustrequire the vendor/autoload.php file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

Usage

The Process class executes a command in asub-process, taking care of the differences between operating system andescaping arguments to prevent security issues. It replaces PHP functions likeexec, passthru, shell_exec andsystem:

  1. use Symfony\Component\Process\Exception\ProcessFailedException;
  2. use Symfony\Component\Process\Process;
  3.  
  4. $process = new Process(['ls', '-lsa']);
  5. $process->run();
  6.  
  7. // executes after the command finishes
  8. if (!$process->isSuccessful()) {
  9. throw new ProcessFailedException($process);
  10. }
  11.  
  12. echo $process->getOutput();

The getOutput() method always returns the whole content of the standardoutput of the command and getErrorOutput() the content of the erroroutput. Alternatively, the getIncrementalOutput()and getIncrementalErrorOutput()methods return the new output since the last call.

The clearOutput() method clearsthe contents of the output andclearErrorOutput() clearsthe contents of the error output.

You can also use the Process class with theforeach construct to get the output while it is generated. By default, the loop waitsfor new output before going to the next iteration:

  1. $process = new Process(['ls', '-lsa']);
  2. $process->start();
  3.  
  4. foreach ($process as $type => $data) {
  5. if ($process::OUT === $type) {
  6. echo "\nRead from stdout: ".$data;
  7. } else { // $process::ERR === $type
  8. echo "\nRead from stderr: ".$data;
  9. }
  10. }

Tip

The Process component internally uses a PHP iterator to get the output whileit is generated. That iterator is exposed via the getIterator() methodto allow customizing its behavior:

  1. $process = new Process(['ls', '-lsa']);
  2. $process->start();
  3. $iterator = $process->getIterator($process::ITER_SKIP_ERR | $process::ITER_KEEP_OUTPUT);
  4. foreach ($iterator as $data) {
  5. echo $data."\n";
  6. }

The mustRun() method is identical to run(), except that it will throwa ProcessFailedExceptionif the process couldn't be executed successfully (i.e. the process exitedwith a non-zero code):

  1. use Symfony\Component\Process\Exception\ProcessFailedException;
  2. use Symfony\Component\Process\Process;
  3.  
  4. $process = new Process(['ls', '-lsa']);
  5.  
  6. try {
  7. $process->mustRun();
  8.  
  9. echo $process->getOutput();
  10. } catch (ProcessFailedException $exception) {
  11. echo $exception->getMessage();
  12. }

Using Features From the OS Shell

Using array of arguments is the recommended way to define commands. Thissaves you from any escaping and allows sending signals seamlessly(e.g. to stop processes before completion):

  1. $process = new Process(['/path/command', '--option', 'argument', 'etc.']);
  2. $process = new Process(['/path/to/php', '--define', 'memory_limit=1024M', '/path/to/script.php']);

If you need to use stream redirections, conditional execution, or any otherfeature provided by the shell of your operating system, you can also definecommands as strings using thefromShellCommandline() staticfactory.

Each operating system provides a different syntax for their command-lines,so it becomes your responsibility to deal with escaping and portability.

When using strings to define commands, variable arguments are passed asenvironment variables using the second argument of the run(),mustRun() or start() methods. Referencing them is also OS-dependent:

  1. // On Unix-like OSes (Linux, macOS)
  2. $process = Process::fromShellCommandline('echo "$MESSAGE"');
  3.  
  4. // On Windows
  5. $process = Process::fromShellCommandline('echo "!MESSAGE!"');
  6.  
  7. // On both Unix-like and Windows
  8. $process->run(null, ['MESSAGE' => 'Something to output']);

Setting Environment Variables for Processes

The constructor of the Process class andall of its methods related to executing processes (run(), mustRun(),start(), etc.) allow passing an array of environment variables to set whilerunning the process:

  1. $process = new Process(['...'], null, ['ENV_VAR_NAME' => 'value']);
  2. $process = Process::fromShellCommandline('...', null, ['ENV_VAR_NAME' => 'value']);
  3. $process->run(null, ['ENV_VAR_NAME' => 'value']);

In addition to the env vars passed explicitly, processes inherit all the envvars defined in your system. You can prevent this by setting to false theenv vars you want to remove:

  1. $process = new Process(['...'], null, [
  2. 'APP_ENV' => false,
  3. 'SYMFONY_DOTENV_VARS' => false,
  4. ]);

Getting real-time Process Output

When executing a long running command (like rsync-ing files to a remoteserver), you can give feedback to the end user in real-time by passing ananonymous function to therun() method:

  1. use Symfony\Component\Process\Process;
  2.  
  3. $process = new Process(['ls', '-lsa']);
  4. $process->run(function ($type, $buffer) {
  5. if (Process::ERR === $type) {
  6. echo 'ERR > '.$buffer;
  7. } else {
  8. echo 'OUT > '.$buffer;
  9. }
  10. });

Note

This feature won't work as expected in servers using PHP output buffering.In those cases, either disable the output_buffering PHP option or use theob_flush PHP function to force sending the output buffer.

Running Processes Asynchronously

You can also start the subprocess and then let it run asynchronously, retrievingoutput and the status in your main process whenever you need it. Use thestart() method to start an asynchronousprocess, the isRunning() methodto check if the process is done and thegetOutput() method to get the output:

  1. $process = new Process(['ls', '-lsa']);
  2. $process->start();
  3.  
  4. while ($process->isRunning()) {
  5. // waiting for process to finish
  6. }
  7.  
  8. echo $process->getOutput();

You can also wait for a process to end if you started it asynchronously andare done doing other stuff:

  1. $process = new Process(['ls', '-lsa']);
  2. $process->start();
  3.  
  4. // ... do other things
  5.  
  6. $process->wait();
  7.  
  8. // ... do things after the process has finished

Note

The wait() method is blocking,which means that your code will halt at this line until the externalprocess is completed.

Note

If a Response is sent before a child process had a chance to complete,the server process will be killed (depending on your OS). It means thatyour task will be stopped right away. Running an asynchronous processis not the same as running a process that survives its parent process.

If you want your process to survive the request/response cycle, you cantake advantage of the kernel.terminate event, and run your commandsynchronously inside this event. Be aware that kernel.terminateis called only if you use PHP-FPM.

Caution

Beware also that if you do that, the said PHP-FPM process will not beavailable to serve any new request until the subprocess is finished. Thismeans you can quickly block your FPM pool if you're not careful enough.That is why it's generally way better not to do any fancy things evenafter the request is sent, but to use a job queue instead.

wait() takes one optional argument:a callback that is called repeatedly whilst the process is still running, passingin the output and its type:

  1. $process = new Process(['ls', '-lsa']);
  2. $process->start();
  3.  
  4. $process->wait(function ($type, $buffer) {
  5. if (Process::ERR === $type) {
  6. echo 'ERR > '.$buffer;
  7. } else {
  8. echo 'OUT > '.$buffer;
  9. }
  10. });

Instead of waiting until the process has finished, you can use thewaitUntil() method to keep or stopwaiting based on some PHP logic. The following example starts a long runningprocess and checks its output to wait until its fully initialized:

  1. $process = new Process(['/usr/bin/php', 'slow-starting-server.php']);
  2. $process->start();
  3.  
  4. // ... do other things
  5.  
  6. // waits until the given anonymous function returns true
  7. $process->waitUntil(function ($type, $output) {
  8. return $output === 'Ready. Waiting for commands...';
  9. });
  10.  
  11. // ... do things after the process is ready

Streaming to the Standard Input of a Process

Before a process is started, you can specify its standard input using either thesetInput() method or the 4th argumentof the constructor. The provided input can be a string, a stream resource or aTraversable object:

  1. $process = new Process(['cat']);
  2. $process->setInput('foobar');
  3. $process->run();

When this input is fully written to the subprocess standard input, the correspondingpipe is closed.

In order to write to a subprocess standard input while it is running, the componentprovides the InputStream class:

  1. $input = new InputStream();
  2. $input->write('foo');
  3.  
  4. $process = new Process(['cat']);
  5. $process->setInput($input);
  6. $process->start();
  7.  
  8. // ... read process output or do other things
  9.  
  10. $input->write('bar');
  11. $input->close();
  12.  
  13. $process->wait();
  14.  
  15. // will echo: foobar
  16. echo $process->getOutput();

The write() method accepts scalars,stream resources or Traversable objects as argument. As shown in the above example,you need to explicitly call the close()method when you are done writing to the standard input of the subprocess.

Using PHP Streams as the Standard Input of a Process

The input of a process can also be defined using PHP streams:

  1. $stream = fopen('php://temporary', 'w+');
  2.  
  3. $process = new Process(['cat']);
  4. $process->setInput($stream);
  5. $process->start();
  6.  
  7. fwrite($stream, 'foo');
  8.  
  9. // ... read process output or do other things
  10.  
  11. fwrite($stream, 'bar');
  12. fclose($stream);
  13.  
  14. $process->wait();
  15.  
  16. // will echo: 'foobar'
  17. echo $process->getOutput();

Stopping a Process

Any asynchronous process can be stopped at any time with thestop() method. This method takestwo arguments: a timeout and a signal. Once the timeout is reached, the signalis sent to the running process. The default signal sent to a process is SIGKILL.Please read the signal documentation belowto find out more about signal handling in the Process component:

  1. $process = new Process(['ls', '-lsa']);
  2. $process->start();
  3.  
  4. // ... do other things
  5.  
  6. $process->stop(3, SIGINT);

Executing PHP Code in Isolation

If you want to execute some PHP code in isolation, use the PhpProcessinstead:

  1. use Symfony\Component\Process\PhpProcess;
  2.  
  3. $process = new PhpProcess(<<<EOF
  4. <?= 'Hello World' ?>
  5. EOF
  6. );
  7. $process->run();

Process Timeout

By default processes have a timeout of 60 seconds, but you can change it passinga different timeout (in seconds) to the setTimeout() method:

  1. use Symfony\Component\Process\Process;
  2.  
  3. $process = new Process(['ls', '-lsa']);
  4. $process->setTimeout(3600);
  5. $process->run();

If the timeout is reached, aProcessTimedOutException is thrown.

For long running commands, it is your responsibility to perform the timeoutcheck regularly:

  1. $process->setTimeout(3600);
  2. $process->start();
  3.  
  4. while ($condition) {
  5. // ...
  6.  
  7. // check if the timeout is reached
  8. $process->checkTimeout();
  9.  
  10. usleep(200000);
  11. }

Process Idle Timeout

In contrast to the timeout of the previous paragraph, the idle timeout onlyconsiders the time since the last output was produced by the process:

  1. use Symfony\Component\Process\Process;
  2.  
  3. $process = new Process(['something-with-variable-runtime']);
  4. $process->setTimeout(3600);
  5. $process->setIdleTimeout(60);
  6. $process->run();

In the case above, a process is considered timed out, when either the total runtimeexceeds 3600 seconds, or the process does not produce any output for 60 seconds.

Process Signals

When running a program asynchronously, you can send it POSIX signals with thesignal() method:

  1. use Symfony\Component\Process\Process;
  2.  
  3. $process = new Process(['find', '/', '-name', 'rabbit']);
  4. $process->start();
  5.  
  6. // will send a SIGKILL to the process
  7. $process->signal(SIGKILL);

Process Pid

You can access the pid of a running process with thegetPid() method:

  1. use Symfony\Component\Process\Process;
  2.  
  3. $process = new Process(['/usr/bin/php', 'worker.php']);
  4. $process->start();
  5.  
  6. $pid = $process->getPid();

Disabling Output

As standard output and error output are always fetched from the underlying process,it might be convenient to disable output in some cases to save memory.Use disableOutput() andenableOutput() to toggle this feature:

  1. use Symfony\Component\Process\Process;
  2.  
  3. $process = new Process(['/usr/bin/php', 'worker.php']);
  4. $process->disableOutput();
  5. $process->run();

Caution

You cannot enable or disable the output while the process is running.

If you disable the output, you cannot access getOutput(),getIncrementalOutput(), getErrorOutput(), getIncrementalErrorOutput() orsetIdleTimeout().

However, it is possible to pass a callback to the start, run or mustRunmethods to handle process output in a streaming fashion.

Finding the Executable PHP Binary

This component also provides a utility class calledPhpExecutableFinder which returns theabsolute path of the executable PHP binary available on your server:

  1. use Symfony\Component\Process\PhpExecutableFinder;
  2.  
  3. $phpBinaryFinder = new PhpExecutableFinder();
  4. $phpBinaryPath = $phpBinaryFinder->find();
  5. // $phpBinaryPath = '/usr/local/bin/php' (the result will be different on your computer)

Checking for TTY Support

Another utility provided by this component is a method calledisTtySupported() which returnswhether TTY) is supported on the current operating system:

  1. use Symfony\Component\Process\Process;
  2.  
  3. $process = (new Process())->setTty(Process::isTtySupported());