Check if PID exists on Linux

A simple function that will scan /proc file system and check if PID exists. If name is provided, it will also check the command name. Function returns TRUE if process was found (and name matched if specified) or FALSE if no such process ID exists.

 /**
   * Check if process exists on Linux type OS
   *
   * @param int $pid Process ID
   * @param string $name Process name, null for no process name matching
   * @return bool
   */
  function checkProcess($pid, $name = null){
    // form the filename to search for
    $file = '/proc/' . (int)$pid . '/cmdline';
    $fp = false;
    if (file_exists($file))
      $fp = @fopen($file, 'r');
    // if file does not exist or cannot be opened, return false
    if (!$fp)
      return false;
    $buf = fgets($fp);
    // if we failed to read from file, return false
    if ($buf === false){
      return false;
    }
    if ($name !== null){
      // this code will also check if name matches
      $cmd = basename($buf);
      if (preg_match('/' . $name . '.*/', $cmd)){
        fclose($fp);
        return true;
      }
      else {
        // process was found, but name did not match
        fclose($fp);
        return false;
      }
    } else {
      // process found, name is null, return true
      fclose($fp);
      return true;
    }
  }

Tags: , , , , ,

 
 
 
Content not available.
Please allow cookies by clicking Accept on the banner

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close