At 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.
I just wanted to post that you can use -C with ps to search by command name:
root@andLinux:~$ ps -C ssh
PID TTY TIME CMD
13413 pts/1 00:00:00 ssh
13486 pts/2 00:00:01 ssh
13698 pts/3 00:00:00 ssh
root@andLinux:~$ ps -C ssha
PID TTY TIME CMD
tnx marc,
this saved my some typing
… to chech if a processname (and not a pid) is running I did this
$cmd = “ps -ef | grep processname “;
ps returns an exit status of 1 if there are no processes, so you can just use that
or just use posix_getsid($pid); returns false if process is not found