Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP CLI in Windows: Handling Ctrl-C commands?

Tags:

php

windows

pcntl

How can I handle CTRL+C in PHP on the command line? Pcntl_* functions do not work in Windows.

like image 602
x74x61 Avatar asked Mar 01 '12 20:03

x74x61


1 Answers

As of PHP 7.4, this is now possible by registering a handler callback with the sapi_windows_set_ctrl_handler() function.

This is complemented by sapi_windows_generate_ctrl_event(), which can be used to dispatch signals to other processes attached to the same console as the caller.

Only the CTRL-C and CTRL-BREAK events can be handled in user space, the close/log-off/shutdown events cannot be implented safely as the operating system will likely be in an unpredictable state of partial shutdown by the time the handler function is invoked, so there is a risk that any code executed at this point will do more harm than good.

You can find more information about the underlying mechanism on MSDN:

  • SetConsoleCtrlHandler()
  • GenerateConsoleCtrlEvent()

The PHP API is almost identical to the underlying C API, the only notable difference being that PHP only permits a single callback to be registered, and consequently the handler does does not have a meaningful return value, the engine simply marks the events as handled. This is in order to keep the implementation simple, as a stack of functions can easily be implemented in userland, and likewise if you don't want to handle an event you can simply call exit.

like image 138
DaveRandom Avatar answered Oct 11 '22 11:10

DaveRandom