PHP CLI in Windows: Handling Ctrl-C commands?
Asked Answered
A

3

13

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

Amarette answered 1/3, 2012 at 20:7 Comment(9)
what are you trying to achieve?Rainarainah
No Windows to test, perhaps w32api_register_function with SetConsoleCtrlHandler, but that's wildly guessing here... and quite possibly wrong.Pierro
@Dagon I need my script to do something when I interrupt it. For example, write in-memory xml dom to file, before quitting.Amarette
sorry it just sounds like a poor designRainarainah
@Dagon What would you suggest?Amarette
you shouldn't have to manually kill a script from the command line.Rainarainah
@Dagon The script takes a LONG time to complete. Perhaps months. It has to keep running continuously without me monitoring it. If there is a better solution, please let me know. Thanks.Amarette
never thought of php as a good language to use for anything but websites, any script that takes over 30 seconds would prod probably be better off being written in an more appropriate language.Rainarainah
for those looking for the reference saying that Pcntl functions are not available on Windows, here's the link php.net/manual/en/pcntl.installation.phpNegligible
P
9

The following works on unix systems.

We can catch keys using stream_get_contents(), but it does not catch the CTRL key. Also filtering ^C does not works.

What we need to do is to catch the SIGINT posix signal.

To supress CTRL + c default behavior.

Program won't quit, you need then to implement another way of exiting!:

function shutdown(){};
pcntl_signal(SIGINT,"shutdown");

To handle CTRL + c, and run some code before exiting:

function shutdown(){
    echo "\033c";                                        // Clear terminal
    system("tput cnorm && tput cup 0 0 && stty echo");   // Restore cursor default
    echo PHP_EOL;                                        // New line
    exit;                                                // Clean quit 
}

register_shutdown_function("shutdown");                  // Handle END of script

declare(ticks = 1);                                      // Allow posix signal handling
pcntl_signal(SIGINT,"shutdown");                         // Catch SIGINT, run shutdown()                    

List of POSIX signals:

Php won't catch SIGKILL, can't be.

SIGABRT and SIGIOT
    The SIGABRT and SIGIOT signal is sent to a process to tell it to abort, i.e. to terminate. The signal is usually initiated by the process itself when it calls abort() function of the C Standard Library, but it can be sent to the process from outside like any other signal.
SIGALRM, SIGVTALRM and SIGPROF
    The SIGALRM, SIGVTALRM and SIGPROF signal is sent to a process when the time limit specified in a call to a preceding alarm setting function (such as setitimer) elapses. SIGALRM is sent when real or clock time elapses. SIGVTALRM is sent when CPU time used by the process elapses. SIGPROF is sent when CPU time used by the process and by the system on behalf of the process elapses.
SIGBUS
    The SIGBUS signal is sent to a process when it causes a bus error. The conditions that lead to the signal being sent are, for example, incorrect memory access alignment or non-existent physical address.
SIGCHLD
    The SIGCHLD signal is sent to a process when a child process terminates, is interrupted, or resumes after being interrupted. One common usage of the signal is to instruct the operating system to clean up the resources used by a child process after its termination without an explicit call to the wait system call.
SIGCONT
    The SIGCONT signal instructs the operating system to continue (restart) a process previously paused by the SIGSTOP or SIGTSTP signal. One important use of this signal is in job control in the Unix shell.
SIGFPE
    The SIGFPE signal is sent to a process when it executes an erroneous arithmetic operation, such as division by zero. This may include integer division by zero, and integer overflow in the result of a divide (only INT_MIN/-1, INT64_MIN/-1 and %-1 accessible from C).[2][3].
SIGHUP
    The SIGHUP signal is sent to a process when its controlling terminal is closed. It was originally designed to notify the process of a serial line drop (a hangup). In modern systems, this signal usually means that the controlling pseudo or virtual terminal has been closed.[4] Many daemons will reload their configuration files and reopen their logfiles instead of exiting when receiving this signal.[5] nohup is a command to make a command ignore the signal.
SIGILL
    The SIGILL signal is sent to a process when it attempts to execute an illegal, malformed, unknown, or privileged instruction.
SIGINT
    The SIGINT signal is sent to a process by its controlling terminal when a user wishes to interrupt the process. This is typically initiated by pressing Ctrl+C, but on some systems, the "delete" character or "break" key can be used.[6]
SIGKILL
    The SIGKILL signal is sent to a process to cause it to terminate immediately (kill). In contrast to SIGTERM and SIGINT, this signal cannot be caught or ignored, and the receiving process cannot perform any clean-up upon receiving this signal. The following exceptions apply:

        Zombie processes cannot be killed since they are already dead and waiting for their parent processes to reap them.
        Processes that are in the blocked state will not die until they wake up again.
        The init process is special: It does not get signals that it does not want to handle, and thus it can ignore SIGKILL.[7] An exception from this exception is while init is ptraced on Linux.[8][9]
        An uninterruptibly sleeping process may not terminate (and free its resources) even when sent SIGKILL. This is one of the few cases in which a UNIX system may have to be rebooted to solve a temporary software problem.

    SIGKILL is used as a last resort when terminating processes in most system shutdown procedures if it does not voluntarily exit in response to SIGTERM. To speed the computer shutdown procedure, Mac OS X 10.6, aka Snow Leopard, will send SIGKILL to applications that have marked themselves "clean" resulting in faster shutdown times with, presumably, no ill effects.[10] The command killall -9 has a similar, while dangerous effect, when executed e.g. in Linux; it doesn't let programs save unsaved data. It has other options, and with none, uses the safer SIGTERM signal.
SIGPIPE
    The SIGPIPE signal is sent to a process when it attempts to write to a pipe without a process connected to the other end.
SIGPOLL
    The SIGPOLL signal is sent when an event occurred on an explicitly watched file descriptor.[11] Using it effectively leads to making asynchronous I/O requests since the kernel will poll the descriptor in place of the caller. It provides an alternative to active polling.
SIGRTMIN to SIGRTMAX
    The SIGRTMIN to SIGRTMAX signals are intended to be used for user-defined purposes. They are real-time signals.
SIGQUIT
    The SIGQUIT signal is sent to a process by its controlling terminal when the user requests that the process quit and perform a core dump.
SIGSEGV
    The SIGSEGV signal is sent to a process when it makes an invalid virtual memory reference, or segmentation fault, i.e. when it performs a segmentation violation.[12]
SIGSTOP
    The SIGSTOP signal instructs the operating system to stop a process for later resumption.
SIGSYS
    The SIGSYS signal is sent to a process when it passes a bad argument to a system call. In practice, this kind of signal is rarely encountered since applications rely on libraries (e.g. libc) to make the call for them. SIGSYS can be received by applications violating the Linux Seccomp security rules configured to restrict them.
SIGTERM
    The SIGTERM signal is sent to a process to request its termination. Unlike the SIGKILL signal, it can be caught and interpreted or ignored by the process. This allows the process to perform nice termination releasing resources and saving state if appropriate. SIGINT is nearly identical to SIGTERM.
SIGTSTP
    The SIGTSTP signal is sent to a process by its controlling terminal to request it to stop (terminal stop). It is commonly initiated by the user pressing Ctrl+Z. Unlike SIGSTOP, the process can register a signal handler for, or ignore, the signal.
SIGTTIN and SIGTTOU
    The SIGTTIN and SIGTTOU signals are sent to a process when it attempts to read in or write out respectively from the tty while in the background. Typically, these signals are received only by processes under job control; daemons do not have controlling terminals and, therefore, should never receive these signals.
SIGTRAP
    The SIGTRAP signal is sent to a process when an exception (or trap) occurs: a condition that a debugger has requested to be informed of – for example, when a particular function is executed, or when a particular variable changes value.
SIGURG
    The SIGURG signal is sent to a process when a socket has urgent or out-of-band data available to read.
SIGUSR1 and SIGUSR2
    The SIGUSR1 and SIGUSR2 signals are sent to a process to indicate user-defined conditions.
SIGXCPU
    The SIGXCPU signal is sent to a process when it has used up the CPU for a duration that exceeds a certain predetermined user-settable value.[13] The arrival of a SIGXCPU signal provides the receiving process a chance to quickly save any intermediate results and to exit gracefully, before it is terminated by the operating system using the SIGKILL signal.
SIGXFSZ
    The SIGXFSZ signal is sent to a process when it grows a file that exceeds the maximum allowed size.
SIGWINCH
    The SIGWINCH signal is sent to a process when its controlling terminal changes its size (a window change).[14]
Papaverine answered 6/10, 2019 at 20:7 Comment(4)
The question is specifically regarding Windows, and specifically indicates that pcntl_signal() handling does not work.Photima
It's not that much out of context... This is an old question,it will help someone in the near future,no worries.Papaverine
@NVRM, yep, it helped me.Psychosomatic
Helped me too. 3 years later.Uganda
E
5

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:

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.

Ensample answered 4/3, 2020 at 4:27 Comment(5)
seems that sapi_windows_set_ctrl_handler does not work in my php-cli 7.4Piperidine
@MichaelQuad I've only experimented with it a little but I have had it working at least kind of PoC in the past, if you link a code sample I should have time to look into it some point over the weekend :-)Ensample
my use-case, i tried to implement: - created new class TempCURLFile which extends CURLFile, of curl api - created an instance of curl and set options for POST transfer (with file) - created sender function that would create a tempnam() file with TempCURLFile - the destructor has unlink($this->name) and some log drop - main code is the busy-wait loop which calls that sender function The problem occurs when php-cli script is terminated(CTRL+C), the last temporary file is not deleted, because __destruct doesn't execute after first sender call, only at the second call.Piperidine
Warning: sapi_windows_set_ctrl_handler(): CTRL events trapping is only supported on console in.. this output i've got.. when running .bat file with php-cli or running php-cli directly from cmd.exe. os windows2008r2 64bit (same as windows7 i suppose)Piperidine
ops, sorry, it was php-cgi.exe, i tried php.exe -q test.php and it worked. handler doesn't run instantly though, while script awaits for curl response it will not react to ctrl+c, but when response arrive (or by timeout of 120sec) it will execute handler function.Piperidine
S
0

If you want to run a task in PHP via command line that takes a very long time, I would try to organize it in badges and keep track of what is already done.

Now you can completely process each badge (ex: process and then store it in an xml file) and not only after the whole list is processed. So a crash/stop in between will only cancel one badge and not all of them.

If you store your current position after each badge somewhere, you can easily resume when your script crashes or is stopped.

Now if you check the OS process-list to see if your script is running, you can write a cron job that starts your script every X minutes if it had crashed and was not already running.

So, TL;DR

  • Process job in small badges
  • Store position of last successfully processed badge
  • Check for already running process at start
  • Continually start script until all are happy!

That aside, I like PHP for small command line jobs but if you have such a large task, something else might be better suited. Check for something that can run stable for a long time and has a means of showing it's progress. Maybe a small C# app with a minimalistic gui.

Sarver answered 11/7, 2013 at 13:57 Comment(2)
That might not be the CtRL+C solution you where looking for but it is a working solution. I highly doubt PHP can handle process aborts! You might however try your luck with "register_shutdown_function"Sarver
Well, there's pcntl_signal, but that's only for Unix systems.Rubi

© 2022 - 2024 — McMap. All rights reserved.