PHP exec 'service httpd fullstatus' 从 cronjob 运行时返回空



我有这个检查服务器负载的脚本。如果负载过高和/或从浏览器访问脚本,脚本将获取所有正在运行的进程。

如果负载太高,并且脚本是从cron作业运行的,则运行的进程将通过邮件发送给我。

My Problem is:当负载过高,并且脚本从cron作业运行时,service httpd fullstatus不返回任何内容。所以我确实收到了一封说明负载的电子邮件。甚至在电子邮件中也显示了ps auxO-C | head。但不是service httpd fullstatus

如果脚本从浏览器中运行,无论负载是否过高,service httpd fullstatusps auxO-C | head都显示正常。

我不明白为什么这是…你们能帮帮我吗?我是在某个地方打错字了,还是我错过了一些限制/概念?

这是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("  ", "&nbsp; ", $ps . "nnnn" . $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("  ", "&nbsp; ", $ps . "nnnn" . $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";
    }
}
?>

如果使用完整路径,则可以解决此问题。例如,对于centos,您可以使用:

/sbin/service HTTPD fullstatus

最新更新