title: Checking if process still running?
body: <p>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 run by cron every 5mn to check whether the process is still running.</p>
  
  <p>Based on <a href="http://php.net/manual/en/function.getmypid.php" rel="noreferrer">this page</a>, I tried the following code, but it always returns True even if I call it with bogus data:</p>
  
  <pre><code>function processExists($file = false) {
      $exists= false;
      $file= $file ? $file : __FILE__;
  
      // Check if file is in process list
      exec("ps -C $file -o pid=", $pids);
      if (count($pids) &gt; 1) {
      $exists = true;
      }
      return $exists;
  }
  
  #if(processExists("lighttpd"))
  if(processExists("dummy"))
      print("Exists\n")
  else
      print("Doesn't exist\n");
  </code></pre>
  
  <p>Next, I tried <a href="https://stackoverflow.com/questions/1626900/how-to-check-if-ruby-script-is-running-in-background-from-php-script">this code</a>...</p>
  
  <pre><code>(exec("ps -A | grep -i 'lighttpd -D' | grep -v grep", $output);)
  print $output;
  </code></pre>
  
  <p>... but don't get what I expect:</p>
  
  <pre><code>/tmp&gt; ./mycron.phpcli 
  Arrayroot:/tmp&gt; 
  </code></pre>
  
  <p>FWIW, this script is run with the CLI version of PHP 5.2.5, and the OS is uClinux 2.6.19.3.</p>
  
  <p>Thank you for any hint.</p>
  
  <hr>
  
  <p>Edit: This seems to work fine</p>
  
  <pre><code>exec("ps aux | grep -i 'lighttpd -D' | grep -v grep", $pids);
  if(empty($pids)) {
          print "Lighttpd not running!\n";
  } else {
          print "Lighttpd OK\n";
  }
  </code></pre>