Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-26.2.0 | composer require openswoole/core:26.2.0
Since: OpenSwoole v26.2.0, PHP 8.4+
In PHP 8.4, exit() was changed from an opcode to a function, which allows OpenSwoole to intercept it. When exit() is called inside a coroutine, OpenSwoole throws an openswoole_exit_exception instead of terminating the entire worker process.
This prevents a single coroutine from crashing the worker and affecting all other active connections and coroutines.
<?php
use OpenSwoole\Http\Server;
use OpenSwoole\Http\Request;
use OpenSwoole\Http\Response;
$server = new Server("0.0.0.0", 9501);
$server->on("request", function (Request $request, Response $response) {
if ($request->get['action'] ?? '' === 'quit') {
// On PHP 8.4+, this throws openswoole_exit_exception
// instead of killing the worker process
$response->end("Exiting coroutine\n");
exit(0);
}
$response->end("Hello World\n");
});
$server->start();
<?php
use OpenSwoole\Coroutine;
Coroutine::set([
'hook_flags' => OpenSwoole\Runtime::HOOK_ALL,
]);
co::run(function () {
go(function () {
try {
echo "Before exit\n";
exit(1);
} catch (\OpenSwoole\ExitException $e) {
echo "Caught exit with status: " . $e->getStatus() . "\n";
}
// Coroutine continues after catching the exception
echo "After exit catch\n";
});
go(function () {
Co::sleep(0.1);
// This coroutine is NOT affected by the exit() in the other coroutine
echo "Other coroutine still running\n";
});
});
<?php
// PHP < 8.4: exit() terminates the entire worker process
// PHP 8.4+ with OpenSwoole 26.2.0: exit() throws openswoole_exit_exception
co::run(function () {
go(function () {
echo "Coroutine 1: working...\n";
Co::sleep(0.5);
exit(0); // Throws exception, only this coroutine is terminated
});
go(function () {
echo "Coroutine 2: working...\n";
Co::sleep(1);
echo "Coroutine 2: still alive!\n"; // This will execute
});
});
exit() is a function rather than an opcodeexit() still terminates the worker processOpenSwoole\ExitException (or openswoole_exit_exception)