sdfor
sdfor

Reputation: 6448

How best to tell a background PHPprogram to stop

I wrote a long running PHP background program. There are times that I want it to stop, but stop gracefully,

What i did was, in the main logic loop I test for the existence of a file with a specific name. If the file exists the program stops. When I want the program to end itself, I just create that file.

Is there a more elegant way to do it.

I don't want to kill the process. I want the program to end itself.

Upvotes: 2

Views: 179

Answers (1)

helmbert
helmbert

Reputation: 38004

As already suggested in comments, you can use a signal to terminate your process. The signal that you'll want to use is the SIGTERM signal (emphasis mine) [ref]:

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.

For this, register a signal handler using the pcntl_signal function before starting your main loop.

declare(ticks = 1);
$stopProcess = FALSE;
pcntl_signal(SIGTERM, function() use (&$stopProcess) {
    echo "Received SIGTERM...\n";
    // Do further cleanup work either here or after the end of your main loop
    $stopProcess = TRUE;
});

while (!$stopProcess) {
    // main work loop
}

// Do cleanup work either here or in your signal handler

On the command line, you can use the kill executable to send the SIGTERM signal to your process:

$ kill -TERM <process id>

Upvotes: 1

Related Questions