Skip to content

Commit d105e10

Browse files
authored
feat: handle Ctrl+C and Ctrl+Break in SignalTrait on Windows (#10699)
1 parent cc0be1b commit d105e10

6 files changed

Lines changed: 502 additions & 6 deletions

File tree

‎docs/changelogs/v4.8.0.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ Release Date: Unreleased
223223
- Likewise, the `command()` function now also supports the above enhancements for command-line option parsing when using the function to run commands from code.
224224
- Added `make:request` generator command to scaffold [Form Request](../incoming/form_requests.md#form-requests) classes.
225225
- Added `key:rotate` command to demote the current `encryption.key` to `encryption.previousKeys` in **.env** and generate a new key. See [Rotating with the `key:rotate` Command](../libraries/encryption.md#rotating-with-the-keyrotate-command).
226+
- `SignalTrait` now handles Ctrl+C and Ctrl+Break on Windows, through `sapi_windows_set_ctrl_handler()`, so a command can stop gracefully there too. The events are reported as `SIGINT` (`2`). See [Windows](../cli/cli_signals.md#windows).
226227
- Added `AbstractCommand::callSilently()` to invoke another command with its output discarded, restoring the prior output afterwards. See [Calling Silently](../cli/cli_modern_commands.md#calling-silently).
227228
- The output side of the `CLI` class now lives in instance classes, with `CLI` delegating to them: `Output` (`print()`, `write()`, `error()`, `newLine()`, `deferNewLine()`, `beep()`, `clearScreen()`, `color()`, `wrap()`), `Terminal` (dimensions and color support), `ProgressBar`, `Table`, and `Color` (ANSI codes and `Color::width()`). `CLI::getOutput()` and `CLI::getTerminal()` return the shared instances. See [The Classes Behind the Facade](../cli/cli_library.md#the-classes-behind-the-facade).
228229
- Modern commands can write through `$this->getOutput()`, the same `Output` used by the static `CLI` methods. `AbstractCommand::run()` and `Commands::runCommand()` accept an `Output` to run against, which `Console` passes down and sub-commands inherit. See [Writing Output](../cli/cli_modern_commands.md#writing-output).

‎docs/cli/cli_signals.md‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,29 @@ These signals are handled directly by the kernel and will terminate or suspend y
3636

3737
Signal handling requires:
3838

39-
- **Unix-based system** (Linux, macOS, BSD) - Windows is not supported
40-
- **PCNTL extension** - for signal registration and handling
41-
- **POSIX extension** - required for pause/resume functionality (SIGTSTP/SIGCONT)
39+
- **Unix-based system** (Linux, macOS, BSD) - see [Windows](#windows) for Windows
40+
- **PCNTL extension** (Unix only) - for signal registration and handling
41+
- **POSIX extension** (Unix only) - required for pause/resume functionality (SIGTSTP/SIGCONT)
4242

4343
!!! note "Note"
4444
On systems without these extensions, the SignalTrait will gracefully degrade and disable signal handling.
4545

46+
### Windows
47+
48+
!!! success "Available from version 4.8.0"
49+
Ctrl+C and Ctrl+Break are handled on Windows.
50+
51+
Windows has no PCNTL extension and no Unix signals. `SignalTrait` handles the one thing Windows can deliver to a PHP script: the console control events produced by **Ctrl+C** and **Ctrl+Break**. They are handled through PHP's `sapi_windows_set_ctrl_handler()` and reported to your command as `SIGINT` (`2`), so `isRunning()`, `shouldTerminate()`, custom handlers, and `onInterruption()` work as they do on Unix.
52+
53+
- Call `registerSignals()` without arguments. The `SIG*` constants come from the PCNTL extension, which is not available on Windows. If you pass a list, it must contain `2`. Every other signal is ignored.
54+
- To map the event to your own method, use `2` as the key: `$this->registerSignals([], [2 => 'handleInterrupt']);`.
55+
- `withSignalsBlocked()` runs the operation without blocking console events. Your handler can run during the operation, as soon as the event arrives.
56+
- Pause and resume (`SIGTSTP` / `SIGCONT`), and every other signal, do not exist on Windows.
57+
- Windows console control handling is available when PHP runs under `cli` or `cli-server`. On other SAPIs, for example when a command runs through `command()` in a controller, `registerSignals()` does nothing.
58+
59+
!!! important "Important"
60+
Once a handler is registered, Ctrl+C and Ctrl+Break no longer end the process. Your command must check `shouldTerminate()` and return, as on Unix.
61+
4662
## Using the SignalTrait
4763

4864
The `SignalTrait` provides a comprehensive signal handling system for CLI commands. To use it, simply add the trait to your command class and register signals in your command's `execute()` method:
@@ -523,7 +539,7 @@ $this->registerSignals(
523539
```
524540

525541
!!! note "Note"
526-
Requires the PCNTL extension. On Windows, signal handling is automatically disabled.
542+
On Unix, registration requires the PCNTL extension. On Windows, only Ctrl+C and Ctrl+Break are handled, as `SIGINT` (`2`). See [Windows](#windows).
527543

528544
#### isRunning()
529545

‎system/CLI/SignalTrait.php‎

Lines changed: 122 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,20 @@
1818
/**
1919
* Signal Trait
2020
*
21-
* Provides PCNTL signal handling capabilities for CLI commands.
22-
* Requires the PCNTL extension (Unix only).
21+
* Provides signal handling capabilities for CLI commands.
22+
*
23+
* On Unix it requires the PCNTL extension. On Windows, where PCNTL does not
24+
* exist, only Ctrl+C and Ctrl+Break are supported, through
25+
* `sapi_windows_set_ctrl_handler()`. Both are reported as SIGINT (2).
2326
*/
2427
trait SignalTrait
2528
{
29+
/**
30+
* The number of SIGINT on every platform that defines it. The SIG*
31+
* constants come from the PCNTL extension, which Windows does not have.
32+
*/
33+
private const INTERRUPT_SIGNAL = 2;
34+
2635
/**
2736
* Whether the process should continue running (false = termination requested).
2837
*/
@@ -47,6 +56,11 @@ trait SignalTrait
4756
*/
4857
private array $signalMethodMap = [];
4958

59+
/**
60+
* Whether the Windows console control handler is registered.
61+
*/
62+
private bool $windowsCtrlHandlerRegistered = false;
63+
5064
/**
5165
* Cached result of PCNTL extension availability.
5266
*/
@@ -86,9 +100,47 @@ protected function isPosixAvailable(): bool
86100
return self::$isPosixAvailable;
87101
}
88102

103+
/**
104+
* Check if the Windows console control handler is available.
105+
*
106+
* It is the Windows counterpart of PCNTL.
107+
*/
108+
protected function isWindowsCtrlHandlerAvailable(): bool
109+
{
110+
// Every Windows build defines the function, but PHP throws an Error when
111+
// it is called outside a console SAPI (`cli`, `cli-server`), for example
112+
// by a command run through `command()` from a web request.
113+
return is_windows()
114+
&& str_starts_with(PHP_SAPI, 'cli')
115+
&& function_exists('sapi_windows_set_ctrl_handler');
116+
}
117+
118+
/**
119+
* Add or remove the Windows console control handler.
120+
*
121+
* Wraps `sapi_windows_set_ctrl_handler()` so it can be replaced in tests,
122+
* as the function is only available on Windows.
123+
*
124+
* Removing a handler leaves PHP holding the callable it was given. Passing
125+
* `null` with `$add` set to `false` afterwards releases it.
126+
*
127+
* @param (callable(int): void)|null $handler
128+
*/
129+
protected function setWindowsCtrlHandler(?callable $handler, bool $add): bool
130+
{
131+
if (! function_exists('sapi_windows_set_ctrl_handler')) {
132+
return false;
133+
}
134+
135+
return sapi_windows_set_ctrl_handler($handler, $add); // @codeCoverageIgnore
136+
}
137+
89138
/**
90139
* Register signal handlers.
91140
*
141+
* On Windows the SIG* constants are not available, so call it without
142+
* arguments or pass `2`. Any other signal is ignored.
143+
*
92144
* @param list<int> $signals List of signals to handle
93145
* @param array<int, string> $methodMap Optional signal-to-method mapping
94146
*/
@@ -97,6 +149,10 @@ protected function registerSignals(
97149
array $methodMap = [],
98150
): void {
99151
if (! $this->isPcntlAvailable()) {
152+
if ($this->isWindowsCtrlHandlerAvailable()) {
153+
$this->registerWindowsCtrlHandler($signals, $methodMap);
154+
}
155+
100156
return;
101157
}
102158

@@ -131,6 +187,48 @@ protected function registerSignals(
131187
}
132188
}
133189

190+
/**
191+
* Register the Windows console control handler.
192+
*
193+
* @param list<int> $signals List of signals to handle
194+
* @param array<int, string> $methodMap Optional signal-to-method mapping
195+
*/
196+
private function registerWindowsCtrlHandler(array $signals, array $methodMap): void
197+
{
198+
if ($signals !== [] && ! in_array(self::INTERRUPT_SIGNAL, $signals, true)) {
199+
return;
200+
}
201+
202+
$this->signalMethodMap = $methodMap;
203+
204+
if ($this->windowsCtrlHandlerRegistered) {
205+
return;
206+
}
207+
208+
// PHP resolves a callable stored by the native API in the scope it interrupts,
209+
// where the protected method may not be accessible. A Closure is bound already.
210+
if ($this->setWindowsCtrlHandler($this->handleWindowsCtrlEvent(...), true)) {
211+
$this->windowsCtrlHandlerRegistered = true;
212+
$this->registeredSignals[] = self::INTERRUPT_SIGNAL;
213+
} else {
214+
CLI::write(lang('CLI.signals.failedSignal', [$this->getSignalName(self::INTERRUPT_SIGNAL)]), 'red');
215+
}
216+
}
217+
218+
/**
219+
* Handle a Windows console control event.
220+
*
221+
* Windows hands the handler no signal number, so the event is reported as SIGINT.
222+
* Like on Unix, the process is no longer stopped by the event, and the command
223+
* is expected to check `shouldTerminate()` and exit by itself.
224+
*/
225+
protected function handleWindowsCtrlEvent(int $event): void
226+
{
227+
$this->callCustomHandler(self::INTERRUPT_SIGNAL);
228+
229+
$this->running = false;
230+
}
231+
134232
/**
135233
* Handle incoming signals.
136234
*/
@@ -302,6 +400,11 @@ protected function mapSignal(int $signal, string $method): void
302400
*/
303401
protected function getSignalName(int $signal): string
304402
{
403+
// The SIG* constants come from PCNTL, which Windows does not have.
404+
if (! $this->isPcntlAvailable()) {
405+
return $signal === self::INTERRUPT_SIGNAL ? 'SIGINT' : "Signal {$signal}";
406+
}
407+
305408
return match ($signal) {
306409
SIGTERM => 'SIGTERM',
307410
SIGINT => 'SIGINT',
@@ -322,6 +425,23 @@ protected function getSignalName(int $signal): string
322425
*/
323426
protected function unregisterSignals(): void
324427
{
428+
if ($this->windowsCtrlHandlerRegistered) {
429+
// Detaching needs a callable, which PHP then keeps, along with this object.
430+
// Passing null afterwards releases it and leaves Ctrl+C at its default.
431+
if (! $this->setWindowsCtrlHandler($this->handleWindowsCtrlEvent(...), false)) {
432+
// The handler may still be installed: keep the state so removal can be retried.
433+
return;
434+
}
435+
436+
$this->setWindowsCtrlHandler(null, false);
437+
438+
$this->windowsCtrlHandlerRegistered = false;
439+
$this->registeredSignals = [];
440+
$this->signalMethodMap = [];
441+
442+
return;
443+
}
444+
325445
if (! $this->isPcntlAvailable()) {
326446
return;
327447
}

‎tests/_support/Commands/Legacy/SignalCommandNoPcntl.php‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,23 @@ protected function isPcntlAvailable(): bool
2525
{
2626
return false;
2727
}
28+
29+
/**
30+
* Override to simulate no Windows console control handler either,
31+
* so that no native handler is installed when this runs on Windows.
32+
*/
33+
protected function isWindowsCtrlHandlerAvailable(): bool
34+
{
35+
return false;
36+
}
37+
38+
/**
39+
* Calls the native wrapper directly, bypassing the availability check.
40+
*
41+
* @param (callable(int): void)|null $handler
42+
*/
43+
public function testSetWindowsCtrlHandler(?callable $handler, bool $add): bool
44+
{
45+
return $this->setWindowsCtrlHandler($handler, $add);
46+
}
2847
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace Tests\Support\Commands\Legacy;
15+
16+
/**
17+
* Mock command that simulates Windows: no PCNTL or POSIX extension, but a console
18+
* control handler. The handler is recorded instead of being installed,
19+
* as `sapi_windows_set_ctrl_handler()` only exists on Windows.
20+
*/
21+
class SignalCommandWindows extends SignalCommand
22+
{
23+
/**
24+
* Whether the simulated `sapi_windows_set_ctrl_handler()` succeeds.
25+
*/
26+
public bool $ctrlHandlerSucceeds = true;
27+
28+
/**
29+
* The handler the command tried to add (`true`) or remove (`false`), in order.
30+
* A `null` handler releases the callable PHP keeps after a removal.
31+
*
32+
* @var list<array{handler: (callable(int): void)|null, add: bool}>
33+
*/
34+
public array $ctrlHandlerCalls = [];
35+
36+
protected function isPcntlAvailable(): bool
37+
{
38+
return false;
39+
}
40+
41+
protected function isPosixAvailable(): bool
42+
{
43+
return false;
44+
}
45+
46+
protected function isWindowsCtrlHandlerAvailable(): bool
47+
{
48+
return true;
49+
}
50+
51+
protected function setWindowsCtrlHandler(?callable $handler, bool $add): bool
52+
{
53+
$this->ctrlHandlerCalls[] = ['handler' => $handler, 'add' => $add];
54+
55+
return $this->ctrlHandlerSucceeds;
56+
}
57+
58+
public function testHandleWindowsCtrlEvent(int $event): void
59+
{
60+
$this->handleWindowsCtrlEvent($event);
61+
}
62+
}

0 commit comments

Comments
 (0)