OpenSwoole Coroutine System: wait

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

Declaration

<?php OpenSwoole\Coroutine\System::wait(float $timeout = -1): array|false

Parameters

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 outside process to complete before continuing. Using this method will allow the coroutine to yield while waiting for another process to complete, not blocking the current process space. The coroutine resumes when the wait finishes.

You can also use OpenSwoole\Process::wait but take note that pcntl_wait should NOT be used within a coroutine context, it will not work correctly and will block the current process.

When child processes are started from the parent, the parent process must always call Coroutine System functions wait() or waitPid() so that resources can be freed up when those processes are done. Otherwise if the parent does not wait, the child processes will end up becoming zombie processes and wasting system resources.

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 Process(function()
{
    echo "Hello, from a OpenSwoole child process\n";
    sleep(1);
    echo "Child process exciting...\n";
});

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

// Entering the coroutine context
co::run(function() use ($process)
{
    // Default timeout of -1 which means wait forever
    $status = Co\System::wait();

    var_dump(assert($status['pid'] === $process->pid));

    var_dump($status);
});

Output:


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