OpenSwoole Server addProcess

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Server->addProcess(OpenSwoole\Process $process): bool

Parameters

process

The OpenSwoole process object you want to add to the server

Return

success

If success, it returns a true otherwise it returns false.

Description

Attach a user defined Linux process (OpenSwoole Process) to the OpenSwoole Server. The process will be managed by OpenSwoole Server and can also access the status of OpenSwoole Server and communicate with it.

This function is usually used to create a special worker process for monitoring, reporting or other special tasks which require a separate process away from the main server but still be able to communicate with the outside process.

It is useful to expose the function of a Linux process to a web service.

Example

<?php
$server = new OpenSwoole\Server('127.0.0.1', 9501);

$process = new OpenSwoole\Process(function($process) use ($server)
{
    while(true)
    {
        $msg = $process->read();

        foreach($server->connections as $conn)
        {
            $server->send($conn, $msg);
        }
    }
});

// Attach the new process to the server, this process will be managed by the OpenSwoole server once started
$server->addProcess($process);

$server->on('receive', function ($serv, $fd, $from_id, $data) use ($process)
{
    // Send the data received to all the child processes
    $process->write($data);
});

// Start the OpenSwoole server and our new process
$server->start();

The process does not need to be started before the server as the OpenSwoole server will handle that for you when you boot up your server.

Things to Consider

  • A child process has access to the Swoole server that it is attached to so you can use the normal OpenSwoole\Server object instance within a process as shown above. You also have access to various other methods like getClientList, getClientInfo and stats etc.

  • Both the worker and task threads have access to this process as well, so they can communicate with it, however, this can not be done with the $server->task\taskwait event/method

  • A user process is similar to the Master and Manager threads, they don't get restarted

  • If the server is shutdown, the SIGTERM signal will be sent to the user process and then closed

  • User processes are managed by the Manager thread, if a fatal error occurs, then the Manager will recreate the process

  • User processes will not trigger any onWorker* events

Last updated on September 1, 2022