Hacktoberfest 2026: những issue maintainer đã đánh dấu cho tháng Mười, đang mở và phù hợp người mới. Xem issue Hacktoberfest

SignalLoop constructor overrides existing signal handlers, breaking graceful shutdown in Symfony Console commands

Đang mở
#347 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
1-2 ngày
Mức phù hợp với người mới
52/100
Loại issue
Lỗi
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
php, symfony
Lĩnh vực
backend

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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

Ngôn ngữ chính
PHP
Star
60
Fork
32
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của yiisoft/queue

Tất cả issue của yiisoft/queue

Issue tương tự

Thêm issue về PHP

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.