Handling signals in PHP is really not to difficult once you get the hang of it. What’s a signal? When an operating system wants a process to terminate, it will usually send the SIGTERM signal (terminate). SIGTERM is essentially a request. It tells the program “I would really really really like you to shut down”. Most programs, being polite do so. There are many signals which you can see in your man pages (man 7 signal), but just a couple of important ones. kill sends a SIGTERM, Ctrl-C sends SIGINT, closing your terminal sends SIGHUP. SIGKILL can’t be handled and typically kills the process immediately .
The code below shows a simple sleep script that handles signals. Run it, note the PID it prints out and then while it is running send it a signal. You can send signals manually with the kill command:
eg.if 12345 were your process ID:
kill -s SIGTERM 12345
kill -s SIGINT 12345
#!/usr/bin/php -q
<?php
declare(ticks = 1); // how often to check for signals
function sig_handler($signo){ // this function will process sent signals
if ($signo == SIGTERM || $signo == SIGHUP || $signo == SIGINT){
print "\tGrandchild : "
.getmypid()
. " I got signal $signo and will exit!\n";
// If this were something important we might do data cleanup here
exit();
}
}
// These define the signal handling
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
pcntl_signal(SIGINT, "sig_handler");
print "Grandchild : ".getmypid()."\n";
sleep(15);
print "\tGrandchild : " . getmypid() . " exiting\n";
exit();
?>
That’s all there is to it!
This little code snipped ties in closely with a post I have set for tomorrow — Writing daemons in PHP!









wrong. this is just wrong
;)