PHP.GT

Daemon documentation

A software daemon is a background process that runs continuously on a system, often to perform tasks or provide services without direct user interaction. This repository provides a simple API to create and manage running processes, and allows you to bundle processes into pools to be interacted with as a single unit.

Daemon lets our PHP code start operating system commands, read their output while they run, and group several commands together as one pool.

This is useful when a PHP script needs to supervise another process without waiting for it to finish straight away. For example, we might start a development server, run a build step, or stream the output of several long-running commands into one CLI program.

[!NOTE] This package can be used on its own with Composer, but is included by default in WebEngine projects, where it is normally used in higher-level commands, such as gt start, rather than instantiating GT\Daemon\Process from page logic.

Requirements

Install the package with Composer:

composer require phpgt/daemon

The package requires PHP 8.1 or newer and the pcntl extension. It also uses PHP’s built-in proc_open functions, so it needs to run in an environment where process execution is allowed.

A small example

use GT\Daemon\Process;

$process = new Process(PHP_BINARY, "-r", "echo 'Hello from the child process' . PHP_EOL;");
$process->exec();

while($process->isRunning()) {
	echo $process->getOutput();
	usleep(100_000);
}

echo $process->getOutput();
echo "Exit code: " . $process->getExitCode() . PHP_EOL;

The command is passed as separate arguments. In the example above, PHP_BINARY is the executable, -r is the first argument, and the inline PHP code is the second argument.


The overview page shows how to run one command and read its output.