Check if Linux Process is Still Alive from PHP
By marc • Apr 28th, 2008 • Category: PHPAt some point you may need to figure out if a system process is still running from within a PHP application. The secret is by running a system command from PHP that returns the information for a specific process id (PID).
The normal shell command would be something like this:
-
-
$ ps 4946
Which would return something like this:
-
-
PID TTY STAT TIME COMMAND
-
4946 pts/5 S 0:04 php /home/me/background_process.php
As you can see, if the process is still running we get back two lines of information (the header and the actual information).
However, if the process was dead this would have been returned:
-
-
PID TTY STAT TIME COMMAND
So to check the status from a PHP script, we just need to run the command, grab the output, and count the number of lines returned. If less than two lines are returned, then the process is dead.
Here’s an example PHP function:
-
-
function checkPid($pid)
-
{
-
// create our system command
-
$cmd = "ps $pid";
-
-
// run the system command and assign output to a variable ($output)
-
exec($cmd, $output, $result);
-
-
// check the number of lines that were returned
-
if(count($output) >= 2){
-
-
// the process is still alive
-
return true;
-
}
-
-
// the process is dead
-
return false;
-
}
Check out my other post on how to determine the PID of a script from within itself. You will probably need to know this if you want to use the above technique to check the process of a running PHP script.