This read-only repository mirrors
packages/process. Open issues and pull requests in the thesis-php/thesis monorepo.
Run a Unix worker in a group of thesis/async. The group owns the child until it exits. When the group closes, it kills and reaps any worker still running.
Install with composer require thesis/process. Requires PHP 8.6 on Unix with ext-pcntl.
Pass the command as an array of arguments. The child inherits standard input, output and error. Use an extra descriptor for the worker protocol so that logs can still go to stderr.
use Thesis\Async\Group;
use Thesis\Io\Stream;
use Thesis\Process;
use function Thesis\Async\group;
$status = group(static function (Group $group) {
[$parent, $child] = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, 0);
$ipc = new Stream($parent);
try {
$worker = Process::start(
group: $group,
command: [PHP_BINARY, __DIR__.'/worker.php'],
descriptors: [3 => $child],
);
} finally {
fclose($child);
}
$ipc->write("ping\n");
$reply = $ipc->read(1);
$ipc->close();
return $worker->wait();
});The parent uses thesis/io for its non-blocking connection. In worker.php:
$ipc = fopen('php://fd/3', 'r+');
if (fgets($ipc) === "ping\n") {
fwrite($ipc, '!');
}Pass cwd to choose the working directory. The child inherits the parent's environment by default.
Passing env supplies the whole child environment.
Descriptor values must be open native files, pipes or socket streams. Use tmpfile() for a temporary file.
The caller owns these streams and can close its copy after startup. Each child inherits stdio and the requested
streams. Other open descriptors above 2 are redirected to /dev/null so a sibling cannot keep an IPC channel alive.
Launch needs a readable /dev/fd or /proc/self/fd and a spare descriptor for each mapping until spawn completes.
Use $worker->pid for logging and $worker->signal(SIGTERM) to request shutdown.
wait() returns the same exit status to every waiter. A normal exit sets $status->code,
including zero. A signal sets $status->signal. Cancelling a wait leaves the child running
under its group. For a graceful pool shutdown, send the workers their shutdown message and
wait for them before leaving the group.