Check if Linux Process is Still Alive from PHP

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:

  1.  
  2. $ ps 4946

Which would return something like this:

  1.  
  2.   PID TTY      STAT   TIME COMMAND
  3.  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:

  1.  
  2.   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:

  1.  
  2. function checkPid($pid)
  3. {
  4.      // create our system command
  5.      $cmd = "ps $pid";
  6.  
  7.      // run the system command and assign output to a variable ($output)
  8.      exec($cmd, $output, $result);
  9.  
  10.      // check the number of lines that were returned
  11.      if(count($output) >= 2){
  12.  
  13.           // the process is still alive
  14.           return true;
  15.      }
  16.  
  17.      // the process is dead
  18.      return false;
  19. }

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.

Tags: ,

About marc

a Senior Software Engineer in Los Angeles, CA. He likes to receive comments :)