Checking if process still running?

后端 未结 9 572
野的像风
野的像风 2020-11-30 03:55

As a way to build a poor-man\'s watchdog and make sure an application is restarted in case it crashes (until I figure out why), I need to write a PHP CLI script that will be

9条回答
  •  鱼传尺愫
    2020-11-30 04:47

    To check whether process is running by its name, you can use pgrep, e.g.

    $is_running = shell_exec("pgrep -f lighttpd");
    

    or:

    exec("pgrep lighttpd", $output, $return);
    if ($return == 0) {
        echo "Ok, process is running\n";
    }
    

    as per this post.

    If you know the PID of the process, you can use one the following functions:

      /**
       * Checks whether the process is running.
       *
       * @param int $pid Process PID.
       * @return bool
       */
      public static function isProcessRunning($pid) {
        // Calling with 0 kill signal will return true if process is running.
        return posix_kill((int) $pid, 0);
      }
    
      /**
       * Get the command of the process.
       * For example apache2 in case that's the Apache process.
       *
       * @param int $pid Process PID.
       * @return string
       */
      public static function getProcessCommand($pid) {
        $pid = (int) $pid;
        return trim(shell_exec("ps o comm= $pid"));
      }
    

    Related: How to check whether specified PID is currently running without invoking ps from PHP?

提交回复
热议问题