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; } }