PHP: what is pcntl_signal used for?
I found a chunk of code that I haven't seen before:
declare(ticks = 1);
pcntl_signal(SIGINT, array($this, "catchSignal"));
pcntl_signal(SIGTERM开发者_运维百科, array($this, "catchSignal"));
I looked up the function in the PHP documentation, but I still don't understand what this is used for. Please help me understand what this is used for and some examples of where this should be implemented.
The declare statement states to check for events every "tick". A "tick" being roughly equal to a line of code. This is used in command line PHP scripts so you can catch interrupts and shutdown the script gracefully instead of just killing it.
The array($this, "catchSignal")
in the pcntl_signal
function is an odd work around (in my opinion) to support "objects" as parameters. Normally you would just do $this->catchSignal()
, but PHP doesn't accept class objects as parameters in this case. Thus the "array" syntax.
Basically, if the script is issued an Interrupt or Termination signal, call the $this->catchSignal()
function before shutting down.
It's used to install signal handlers. Anything else I could say would just be repeating the article.
The main thing to understand about signal handling is that it's a trap into the operating system. Thus, it can happen outside the normal execution path of your code, interrupting it when it might be doing something else. For instance, if you control-C in *nix, it generally kills whatever program is running. But if that program is doing something sensitive, it might be a bad idea to stop immediately. Thus, a durable program will handle a kill signal in a different manner; gracefully stopping what it's doing before terminating it's execution.
pcntl_signal is the way to do this in PHP.
精彩评论