Handling Signals in PHP

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!

This entry was posted in Programming, Projects and tagged , . Bookmark the permalink.

4 Responses to Handling Signals in PHP

  1. stephen says:

    wrong. this is just wrong

    ;)

    • Petre says:

      can you explain why is this worng?
      tthanks

      • stuporglue says:

        It’s just that PHP isn’t typically used for system scripting or writing daemons.

        Other languages like Perl would be more suited in most cases. It’s not that the example here is incorrect, it’s just that a lot of people (myself included) would usually think that PHP is the wrong tool for the job.

        In my specific case, our daemons needed to integrate with some other PHP classes we had written, so it seemed like the right choice. It’s worked out pretty well I’d say.

  2. Pingback: How to get list of running php scripts using PHP exec()? - PHP Solutions - Developers Q & A

Leave a Reply

Your email address will not be published. Required fields are marked *