Signals in PHP

Our program demonstrates how to handle Unix signals in PHP. Here’s the full source code:

<?php

// Sometimes we'd like our PHP programs to intelligently
// handle Unix signals. For example, we might want a server
// to gracefully shutdown when it receives a SIGTERM, or
// a command-line tool to stop processing input if it
// receives a SIGINT. Here's how to handle signals in PHP.

// PHP signal handling works by registering callback functions
// for specific signals.
function signalHandler($signo) {
    switch ($signo) {
        case SIGINT:
            echo "Caught SIGINT\n";
            exit;
        case SIGTERM:
            echo "Caught SIGTERM\n";
            exit;
        default:
            // Handle other signals
            break;
    }
}

// Register the signal handler for SIGINT and SIGTERM
pcntl_signal(SIGINT, "signalHandler");
pcntl_signal(SIGTERM, "signalHandler");

echo "Awaiting signal...\n";

// This loop simulates a long-running process
while (true) {
    // The pcntl_signal_dispatch() function checks if any signals
    // have been received and calls the appropriate signal handler.
    pcntl_signal_dispatch();
    
    // Simulate some work
    sleep(1);
}

// The program will never reach this point unless
// a signal is received and handled.
echo "Exiting\n";

When we run this program, it will block waiting for a signal. By using Ctrl+C (which the terminal shows as ^C), we can send a SIGINT signal, causing the program to print “Caught SIGINT” and then exit.

$ php signals.php
Awaiting signal...
^C
Caught SIGINT

Note that PHP’s signal handling is only available when PHP is compiled with the --enable-pcntl option, which is typically the case for CLI installations but not for web server modules.

Also, unlike the Go example which uses channels, PHP uses callback functions for signal handling. The pcntl_signal_dispatch() function is used to check for and dispatch signals in the main loop, which is necessary because PHP doesn’t handle signals asynchronously by default.

This approach allows PHP scripts to respond to Unix signals, enabling more robust command-line tools and long-running processes.