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.
Based on this page, I tried the following code, but it always returns True even if I call it with bogus data:
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) > 1) {
$exists = true;
}
return $exists;
}
#if(processExists("lighttpd"))
if(processExists("dummy"))
print("Exists\n")
else
print("Doesn't exist\n");
Next, I tried this code...
(exec("ps -A | grep -i 'lighttpd -D' | grep -v grep", $output);)
print $output;
... but don't get what I expect:
/tmp> ./mycron.phpcli
Arrayroot:/tmp>
FWIW, this script is run with the CLI version of PHP 5.2.5, and the OS is uClinux 2.6.19.3.
Thank you for any hint.
Edit: This seems to work fine
exec("ps aux | grep -i 'lighttpd -D' | grep -v grep", $pids);
if(empty($pids)) {
print "Lighttpd not running!\n";
} else {
print "Lighttpd OK\n";
}
You can try this, which combines bits of those two approaches:
If that doesn't work, you may want to just try running the ps command on your system and seeing what output it gives.
To check whether process is running by its name, you can use
pgrep
, e.g.or:
as per this post.
If you know the PID of the process, you can use one the following functions:
Related: How to check whether specified PID is currently running without invoking ps from PHP?
I'd use
pgrep
to do this (caution, untested code):I have a bash script that does something similar (but with SSH tunnels):
You could alter this script with the commands that you want to monitor.
I didn't see this mentioned here, but here's another approach taking the second grep out of the equation, i use this with alot of my PHP scripts and should work universally
Enjoy.
If you're doing it in php, why not use php code:
In the running program:
Then, in the watchdog program, all you need to do is:
Basically, posix_kill has a special signal
0
that doesn't actually send a signal to the process, but it does check to see if a signal can be sent (the process is actually running).And yes, I do use this quite often when I need long running (or at least watchable) php processes. Typically I write init scripts to start the PHP program, and then have a cron watchdog to check hourly to see if it's running (and if not restart it)...
Try this one
Function checks whether process file is exists in
/proc/
root directory. Works for Linux only