Swoole Coroutine System: wait

Notice: the documentation is suitable for PHP extension swoole until v4.7.1, we only support PHP extension openswoole from v4.7.1

Declaration

<?php
Swoole\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 Swoole\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 Swoole\Process;
use Swoole\Coroutine;
use Swoole\Coroutine\System;

// Creating our process outside of any coroutines, in the main process space
$process = new Process(function()
{
    echo "Hello, from a Swoole 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 Swoole child process
Child process exciting...
bool(true)
array(3) {
  ["pid"]=>
  int(10546)
  ["code"]=>
  int(0)
  ["signal"]=>
  int(0)
}