SignalLoop constructor overrides existing signal handlers, breaking graceful shutdown in Symfony Console commands
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 1-2 días
- Aptitud para principiantes
- 52/100
Línea de trabajo
Start with src/Cli/SignalLoop.php, where the issue identifies constructor calls to pcntl_signal() as the source of the handler replacement. Trace how queue consumers use SignalLoop and check whether signal registration can be limited to an explicitly started processing loop. Done means constructing SignalLoop preserves existing handlers while queue consumers can still handle shutdown signals; the issue names no test file.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Description
Description
Yiisoft\Queue\Cli\SignalLoop unconditionally registers global signal handlers in its constructor, overriding handlers previously registered by other components, such as Symfony Console's SignalRegistry.
This causes custom Yii3 console commands implementing SignalableCommandInterface to stop responding to SIGINT (Ctrl+C) and SIGTERM when SignalLoop is instantiated after Symfony Console has registered its handlers.
The issue can occur indirectly when SignalLoop is instantiated through the DI container, making the behavior dependent on service initialization order.
Root cause
The problem originates in src/Cli/SignalLoop.php:
public function __construct(protected int $memorySoftLimit = 0)
{
foreach (self::SIGNALS_EXIT as $signal) {
pcntl_signal($signal, fn() => $this->exit = true);
}
foreach (self::SIGNALS_SUSPEND as $signal) {
pcntl_signal($signal, fn() => $this->pause = true);
}
foreach (self::SIGNALS_RESUME as $signal) {
pcntl_signal($signal, fn() => $this->pause = false);
}
}
Calling pcntl_signal() replaces the previously registered handler for the given signal.
As a result, simply constructing SignalLoop modifies global process state, even when the instance is never used to run a queue consumer.
For example, when Symfony Console has already registered its SIGINT handler:
Symfony\Component\Console\SignalRegistry\SignalRegistry::handle
Creating a SignalLoop replaces it with:
Closure (Yiisoft\Queue\Cli\SignalLoop)
Consequently, Symfony Console can no longer dispatch the signal to the command's handleSignal() method.
Steps to reproduce
Create the following console command in a Yii3 application with yiisoft/queue, Symfony Console and the PCNTL extension installed.
<?php
declare(strict_types=1);
namespace App\Console;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\SignalableCommandInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Yiisoft\Queue\Cli\SignalLoop;
use Yiisoft\Yii\Console\ExitCode;
#[AsCommand(
name: 'test:handler',
description: 'Signal handler test with SignalLoop',
)]
final class HandlerTestCommand extends Command implements SignalableCommandInterface
{
private bool $shutdown = false;
/**
* SIGINT = Ctrl+C, SIGTERM = Supervisor stop.
* Requires ext-pcntl on the CLI process.
*
* @return list<int>
*/
public function getSubscribedSignals(): array
{
return [SIGINT, SIGTERM];
}
public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false
{
echo "Signal handled\n";
$this->shutdown = true;
return false;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->debugSignalHandler('before', $output);
new SignalLoop();
$this->debugSignalHandler('after', $output);
while (!$this->shutdown) {
echo '.';
sleep(2);
}
return ExitCode::OK;
}
private function debugSignalHandler(
string $stage,
OutputInterface $output,
): void {
$handler = pcntl_signal_get_handler(SIGINT);
if ($handler instanceof \Closure) {
$reflection = new \ReflectionFunction($handler);
$output->writeln(sprintf(
'[%s] SIGINT Closure: %s:%d-%d, scope=%s, captures=%s',
$stage,
$reflection->getFileName() ?: 'unknown',
$reflection->getStartLine(),
$reflection->getEndLine(),
$reflection->getClosureScopeClass()?->getName() ?? 'none',
implode(', ', array_keys($reflection->getStaticVariables())),
));
return;
}
$handlerName = match (true) {
is_array($handler) && is_object($handler[0] ?? null) =>
$handler[0]::class . '::' . $handler[1],
is_int($handler) => (string) $handler,
default => get_debug_type($handler),
};
$output->writeln(sprintf(
'[%s] SIGINT handler: %s',
$stage,
$handlerName,
));
}
}
Register the command in Yii3 and execute:
./yii test:handler
The command should be registered in a way that allows Symfony Console to recognize its SignalableCommandInterface implementation.
Press Ctrl+C while the command is running.
Actual behavior
The output demonstrates that SignalLoop replaces Symfony Console's handler:
[before] SIGINT handler: Symfony\Component\Console\SignalRegistry\SignalRegistry::handle
[after] SIGINT Closure: /app/vendor/yiisoft/queue/src/Cli/SignalLoop.php:30-30, scope=Yiisoft\Queue\Cli\SignalLoop, captures=
...^C.^C.^C.^C.^C.^C...
The process continues running despite repeated Ctrl+C presses.
The command's handleSignal() method is never called, $shutdown remains false, and the loop never terminates gracefully.
Removing this line:
new SignalLoop();
restores the expected behavior.
Expected behavior
Creating a SignalLoop instance should not interfere with signal handlers previously registered by other components.
The existing Symfony Console handler should remain active, allowing the command to receive SIGINT and SIGTERM through SignalableCommandInterface.
After pressing Ctrl+C, the expected behavior is:
[before] SIGINT handler: Symfony\Component\Console\SignalRegistry\SignalRegistry::handle
[after] SIGINT handler: Symfony\Component\Console\SignalRegistry\SignalRegistry::handle
....^CSignal handled
The command should then exit normally with exit code 0.
Queue consumers should still be able to handle shutdown signals when explicitly running their own processing loops.
Impact on real applications
In our application, we encountered this issue in a long-running polling scheduler that interacts with Yii Queue.
Symfony Console initially registered its signal handlers correctly. However, during a scheduler iteration, a dependency was initialized through the DI container, causing SignalLoop to be constructed and replacing Symfony's handlers.
This explains why the scheduler sometimes handled Ctrl+C correctly and sometimes ignored it: the behavior depended on whether SignalLoop was instantiated before or after Symfony Console registered its handlers.
The problem also affects graceful shutdown when the application is stopped by a process supervisor or container runtime using SIGTERM.
Suggested solution
I believe global signal handlers should not be registered as a side effect of constructing a service.
Possible approaches include:
- Moving signal registration out of the SignalLoop constructor and into an explicit lifecycle method.
- Separating signal state management from signal registration.
- Allowing applications or console integrations to control signal registration, using Symfony Console's SignalableCommandInterface where appropriate.
- Ensuring that queue initialization does not overwrite signal handlers owned by other components.
- deally, simply resolving SignalLoop or QueueConsumer from the DI container should not change the application's global signal handling behavior.
Environment
- Yii3 / yiisoft/yii-console
- yiisoft/queue
- Symfony Console
- PHP CLI with PCNTL enabled
Linux
The issue is reproducible without an actual queue connection or message processing — instantiating SignalLoop is sufficient.
Package version
dev-master
PHP version
8.5.11
- Lenguaje dominante
- PHP
- Estrellas
- 60
- Forks
- 32
- Métricas de merge de PR
- Sin PR fusionados en 30 d
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Sin plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de yiisoft/queue
-
Dificultad 5/5 Más de una semana Aptitud para principiantes 35/100
-
Dificultad 5/5 Más de una semana Aptitud para principiantes 35/100
-
Dificultad 4/5 1-2 días Aptitud para principiantes 47/100
-
Dificultad 3/5 1-2 días Aptitud para principiantes 54/100
-
Dificultad 5/5 Más de una semana Aptitud para principiantes 35/100
Todos los issues de yiisoft/queue
Issues similares
-
Dificultad 1/5 Menos de una hora Aptitud para principiantes 90/100
EasyCorp/EasyAdminBundle#7875 ·
Los mantenedores suelen responder en 2 días
-
[Sync EN] PDOException::getCode(): document the int|string return typePosiblemente ocupada @lacatoire la tomó hoy. Abiertosync-en
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
Los mantenedores suelen responder en 1 día
-
sync-en
Dificultad 1/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 2 días
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
coollabsio/coolify#12299 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
Los mantenedores suelen responder en 1 día