问题描述
作为构建穷人看门狗并确保应用程序崩溃的一种方法(直到我弄清原因),我需要编写一个PHP CLI脚本,该脚本将由cron每5百万次运行一次以进行检查该进程是否仍在运行.
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.
基于此页面,我尝试了以下代码,但始终即使我使用虚假数据调用也返回True:
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,此脚本与PHP 5.2.5的CLI版本一起运行,并且操作系统为uClinux 2.6.19.3.
FWIW, this script is run with the CLI version of PHP 5.2.5, and the OS is uClinux 2.6.19.3.
谢谢您的提示.
这似乎工作正常
exec("ps aux | grep -i 'lighttpd -D' | grep -v grep", $pids);
if(empty($pids)) {
print "Lighttpd not running!\n";
} else {
print "Lighttpd OK\n";
}
推荐答案
我将使用pgrep
进行此操作(警告,未经测试的代码):
I'd use pgrep
to do this (caution, untested code):
exec("pgrep lighttpd", $pids);
if(empty($pids)) {
// lighttpd is not running!
}
我有一个执行类似操作的bash脚本(但使用SSH隧道):
I have a bash script that does something similar (but with SSH tunnels):
#!/bin/sh
MYSQL_TUNNEL="ssh -f -N -L 33060:127.0.0.1:3306 tunnel@db"
RSYNC_TUNNEL="ssh -f -N -L 8730:127.0.0.1:873 tunnel@db"
# MYSQL
if [ -z `pgrep -f -x "$MYSQL_TUNNEL"` ]
then
echo Creating tunnel for MySQL.
$MYSQL_TUNNEL
fi
# RSYNC
if [ -z `pgrep -f -x "$RSYNC_TUNNEL"` ]
then
echo Creating tunnel for rsync.
$RSYNC_TUNNEL
fi
您可以使用要监视的命令来更改此脚本.
You could alter this script with the commands that you want to monitor.
这篇关于检查进程是否仍在运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!