Thursday, April 30, 2009

Process Management in PHP

My PHP script downloads a series of binary patches and places them into a directory for further processing. It also creates lock files to prevent two or more instances of my script from being run.

The Problem

When the script receives a SIGINT (Ctrl+C) or SIGTERM signal from the OS, my script is prevented from cleaning up the temporary files, which usually occupies hundreds of MB of space. The lock files also become stale, so my script prevents itself from being run until the next reboot, when the /tmp directory is cleaned up.

The Solution

The solution is to catch the signals so that my script is given one last chance to perform cleanup:
function sig_handler($signo)
{
switch ($signo) {
case SIGTERM:
case SIGQUIT:
case SIGABRT:
case SIGINT:
echo "==> Software Update has been aborted.\n";
echo "==> Performing cleanup...\n";
cleanup();
exit();

break;
default:
// Unknown signal. Do something here...
exit();
}

}

pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGQUIT, "sig_handler");
pcntl_signal(SIGABRT, "sig_handler");
pcntl_signal(SIGINT, "sig_handler");

1 comment:

Alex Gilmor said...

Thanks a lot!!!
This way it finally works without ajax, which I would have hated to use in my current task.