我正在用PHP编写一个网页,它将提供一些有用的工具和与Minecraft服务器相关的信息。
我正在做一个";状态指示器";,检测服务器是否有问题的系统。该系统的一个部分是使用shell_exec检查系统上是否有服务器应用程序运行。我正在使用preg_match来检查shell_exec的结果是否指示有服务器应用程序正在运行。
问题是,无论我做什么,preg_match似乎总是返回false,这表明发生了错误。我找不到关于这个错误的任何细节。
function get_server_app_status($appName)
{
if (preg_match($appName, shell_exec('ps aux | grep ' . $appName . ' | grep -v grep')) != 0)
{
return true;
}
else
{
return false;
}
}
我已经验证了shell_exec通过将其推入变量并使用调试器检查其值以及检查$appName来返回我想要的结果。两者都是字符串,都有我想要的值。
我还检查了preg_match以同样的方式返回的内容,它确实返回了false,而不仅仅是零。
在您的代码片段中:
if (preg_match($appName, shell_exec(...
$appName
是有效的正则表达式吗?
你的意思可能是:
if (preg_match("/" . preg_quote($appName) . "/", shell_exec(...
但是,如果$appName
只是一个字符串,那么您最好只使用字符串比较函数,而不是正则表达式,如strcmp
、strpos
甚至==
。
如果$appName
是字符串而不是正则表达式,只需使用strpos
:
函数get_server_app_status($appName){return strpos($appName,shell_exec('ps aux|grep'.$appName.'|grep-v grep'))!==虚假;}
我实际测试了NULL的返回值。非常成功
function get_server_app_status($appName)
{
$result = shell_exec('ps aux | grep ' . $appName . ' | grep -v grep');
if (!is_null($result)) {
// app is running
} else {
// app is NOT running
}
}
这里有一个使用"pgrep";如果在服务器环境中可用。
<?php
function get_server_app_status($appName) {
return shell_exec("pgrep $appName");
}
// Test driver
echo sprintf("Running: %s" . PHP_EOL, (get_server_app_status('httpd')) ? 'Yes' : 'No');
echo sprintf("Running: %s" . PHP_EOL, (get_server_app_status('java')) ? 'Yes' : 'No');
以下是httpd的输出测试和一个不存在的案例。
./5 proc.php
输出:
Running: Yes
Running: No
注:/5是我的PHP二进制文件的符号链接。