Swoole Server addProcess

Declaration

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

Parameters

process

The Swoole 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 (Swoole Process) to the Swoole Server. The process will be managed by Swoole Server and can also access the status of Swoole 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 Swoole\Server('127.0.0.1', 9501);

$process = new Swoole\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 Swoole 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 Swoole server and our new process
$server->start();

The process does not need to be started before the server as the Swoole 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 Swoole\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