我有这个检查服务器负载的脚本。如果负载太高和/或从浏览器访问脚本,则脚本会获取所有正在运行的进程。
如果负载太高,并且脚本是从 cron 作业运行的,则正在运行的进程会邮寄给我。
我的问题是:
当负载太高,并且脚本是从 cron 作业运行时,service httpd fullstatus
什么也不返回。所以我确实收到了一封说明负载的电子邮件。甚至在ps auxO-C | head
电子邮件中显示。但只是不是service httpd fullstatus
如果脚本是从浏览器运行的,不管负载是否太高,service httpd fullstatus
都ps auxO-C | head
显示ok。
我不明白这是为什么...你们能帮帮我吗?我在某处有错字,还是我错过了一些限制/概念?
这是 crontab:
0,10,20,30,40,50 * * * * /usr/bin/php /var/www/html/loadChecker.php
这是脚本loadChecker.php
:
<?php
define('LOAD_TRIGGER',10); // threshold setting for when to mail the load
// get load average
if (function_exists("sys_getloadavg")){
$content=sys_getloadavg();
$load=$content[0];
$content = implode(" " , $content);
}
else{
$content = file_get_contents("/proc/loadavg");
$loadavg = explode(" ", $content);
$load = $loadavg[0] + 0;
}
if($load >= LOAD_TRIGGER) // check if load is too high
{
// load is too high. If we are in a browser, show running processes, otherwise mail them.
$ps = Array();
exec("ps auxO-C | head", $ps);
$ps = implode("\n", $ps);
$hs = Array();
exec("service httpd fullstatus", $hs);
$hs = implode("\n", $hs);
if (isset($_SERVER['REMOTE_ADDR'])) // are we in a browser?
{
// yes we are. Let's show the PS and HTTPD fullstatus
$output = str_replace("\n", "<br/>\n", str_replace(" ", " ", $ps . "\n\n\n\n" . $hs)); // make it browser friendly
$output = "<html><head></head><body>$output</body></html>";
echo "Load is $content<br/>\n<br/>\n$output";
}
else
{
// no, we're not. Let's mail the PS and HTTPD fullstatus
mail("me@here.com", "Load is $content", "$ps \n \n \n \n$hs "); // BUT THIS FAILS. THE PS IS SHOWN. BUT THE FULLSTATUS IS EMPTY IN THE MAIL
}
}
else
{
// load is OK. If we are in a browser, show running processes
if (isset($_SERVER['REMOTE_ADDR']))
{
$ps = Array();
exec("ps auxO-C | head", $ps);
$ps = implode("\n", $ps);
$hs = Array();
exec("service httpd fullstatus", $hs);
$hs = implode("\n", $hs);
$output = str_replace("\n", "<br/>\n", str_replace(" ", " ", $ps . "\n\n\n\n" . $hs)); // make it browser friendly
$output = "<html><head></head><body>$output</body></html>";
echo "Server load normaal ($content) op webserver3<br/>\n<br/>\n$output";
}
}
?>