Detecting if another copy of a program is running (*NIX specific)
One cute trick, to see if another process is running, is to send it signal 0. Signal 0 does not actually get sent, but kill will check to see if it is possible to send the signal. Note that this only works if you have permission to send a signal to that process.
A practical use for this technique is to avoid running multiple copies of the same program. You save the PID to a file in the usual way... Then during start-up you check the value of the PID file and see if that process currently exists.
This is not totally fool-proof. In rare circumstances it is possible for an unrelated program to have the same recycled PID. But that other program would most likely not accept signals from your program anyway (unless your program is root).
To make it as reliable as possible, you would want your program to remove it's PID file during shutdown (see register_shutdown_function). That way, only if your program crashed AND another program happened to use the same PID AND the other program was willing to accept signals from your program, would you get a wrong result. This would be an exceedingly rare occurrence. This also assumes that the PID file has not been tampered with (as do all programs that rely on PID files...).
It's also possible to use 'ps x' to detect this, but using kill is much more efficient.
Here is the core routine:
$PrevPid = file_get_contents($PathToPidFile);
if(($PrevPid !== FALSE) && posix_kill(rtrim($PrevPid),0)) {
echo "Error: Server is already running with PID: $PrevPid\n";
exit(-99);
} else {
echo "Starting Server...";
}
Hmmm... if you want total 100% reliability, plus efficiency. What you could do is to make the initial check using kill. If it says not running, then you are ready to zoom. But if kill says already running, then you could use:
//You can get the $ProgramName from $argv[0]
$Result = shell_exec('ps x | grep "' . $PrevPid . '" | grep "' . $ProgramName . '" | grep -v "grep"');
Assuming that your program has permissions to do this. If you execute that and get back an empty string, then the other program is an imposter using a recycled PID and you are clear to go.
-- Erik