在PHP CLI中,真的没有办法在Windows中捕获“杀死信号”吗?

Mission: I need to be able to execute a little bit of code when my PHP CLI scripts are "killed"/closed (usually by me Xing down their windows, or from the PC shutting down or rebooting). Ideally, I would want to also be able to instruct the OS to wait as it performs the last bits of some important job, but I've essentially given up on that "dream"...

Problem: Handling such signals in PHP is apparently done with the "PCNTL" extension, which isn't available for Windows at all! This in spite of the fact that PHP is called "cross-platform".

Although the whole point of what I'm doing is for it to be completely OS-agnostic (no, that doesn't mean "runs on any Linux distro", but all current/supported OSes, or at the very least Windows and Mac), I would in this case accept a solution that is Windows-specific. Not happily, but still...

This is not an exact solution to your problem but perhaps can be a workaround solution. If you just want to close some handles, connections, etc.

register_shutdown_function

This solution is very limited

  1. there is no guarantee how many time is given to your script inside the callback
  2. you really should not use any calls to other functions inside the callback - i noticed unpredictable behavior. Sometimes there was no problem and sometimes calls were not executed or only some of them - that was long time ago and by using PHP5.6 - don't know how the behavior is of PHP v7.x
  3. due to point 1. keep your code as simple and short as possible. Perfectly just 10-20 procedural lines. No objects creation, no calls to other functions, avoid static classes as well.
  4. it is up to you to check weather the script shutdown is because it simply ended or there was a problem ot it was terminated. callback passed to shutdown_function will always be called at the end of script. a quick and dirty trick is to put at the end of your script a global variable that is set to true. if a callback registered by shutdown function is called it checks if that variable is set to true. and if so it considers that script is closed normally and if not then an error occurred or script was terminated.

the good side is that this solution once working should be completely independent of target OS.

The second solution to your problem is to use Docker on Windows and Linux and build your application as docker container that starts FROM linux distribution that has the extension PCNTL or using any PHP docker image to start FROM and install the extension on your own by creating a specific Dockerfile. In this approach no matter if the application is run on Windows or Linux you have the PCNTL extension available.

PHP applications in docker can be run from command line almost with the same convenience as standalone php application using a php installed on the host system. So Docker approach seems to be much better.