OpenSwoole Coroutine System: waitPid

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

Declaration

<?php OpenSwoole\Coroutine\System::waitPid(int $pid, float $timeout = -1): array|false

Parameters

pid

The specific Linux process ID to wait for.

timeout

A float in seconds defining how long the process should wait before giving up and returning control. Because a float is used, it means that 2.5 is 2.5 seconds. Minimum value is 0.001 and the default -1 means to never time out, wait for the other process to finish.

Return

Successful operation will return an array which will contain the child process PID, exit code and the type of kill signal that was used. Otherwise false is returned if something went wrong.

Description

Wait for the specified process ID to finish before continuing. This method is basically the same as Co\System::wait(), there is more information there which you should read to understand when processes should be created when using a process inside coroutines.

You can get a specific process ID by using $process->pid, see the example below.

If using a process within coroutines, the process should be created in the main process space first and then used within a coroutine, not the other way round, the example below shows how this can be done. So the process must be created first, this is because at low level it is very complicated to manage processes that are created within a coroutine.


Example

<?php

use OpenSwoole\Process;
use OpenSwoole\Coroutine;
use OpenSwoole\Coroutine\System;

// Creating our process outside of any coroutines, in the main process space
$process = new OpenSwoole\Process(function()
{
    echo "Hello, from a OpenSwoole child process\n";
    sleep(5);
    echo "Child process exciting...\n";
});

// Process does not start until we call
$process->start();

// Entering the coroutine context
co::run(function() use ($process)
{
    // Wait using specific Linux process ID
    $status = Co\System::waitPid($process->pid);
    var_dump($status);
});

Output:

Hello, from a OpenSwoole child process
Child process exciting...
array(3) {
  ["pid"]=>
  int(10549)
  ["code"]=>
  int(0)
  ["signal"]=>
  int(0)
}
Last updated on September 1, 2022