OpenSwoole Server getWorkerPid()

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

Declaration

<?php OpenSwoole\Server->getWorkerPid(int $workerId = -1): int|bool

Parameters

workerId

workerId (optional)

Return

workerPid

Return the current main worker process ID.

Description

Get the worker process Id based on worker Id. If no worker Id is provided, return the process Id of current worker processing the request.

Available since > v4.5.0

Example:

<?php
$serv = new OpenSwoole\Http\Server('127.0.0.1', $pm->getFreePort(), OpenSwoole\Server::POOL_MODE);
$serv->set(array(
    'log_level' => OpenSwoole\Constant::LOG_ERROR,
    'worker_num' => 2,
));
$serv->on("WorkerStart", function (OpenSwoole\Server $serv, $workerId) use ($pm) {
    $GLOBALS['pid_worker_'.$workerId] = posix_getpid();
});
$serv->on('Request', function ($req, $resp) use ($serv) {
    $resp->end(json_encode(['result' =>
        $GLOBALS['pid_worker_'.$serv->worker_id] == $serv->getWorkerPid($serv->worker_id) &&
        $serv->getWorkerPid(0) != $serv->getWorkerPid(1)]
    ));
});
$serv->start();
Last updated on September 20, 2022