查看进程就是使用ps命令而已,只不顾ps的参数太多了。
使用php查询的话,必须要开启几个函数(可以执行外部程序的函数),参考官网:http://php.net/manual/zh/book.exec.php
下面是在php进程中查询某个服务创建的进程数,比如httpd,mysqld,sshd.......
<?php function query_process_num($service){ $res = array(); exec("ps -ef | grep " . $service ." | wc -l", $res); return trim($res[0]) - 2; } echo query_process_num("httpd"); ?>
至于为什么要减2,可以看下面的代码:
<?php
function query_process_num($service){
$res = array();
exec("ps -ef | grep " . $service, $res);
print_r($res);//不处理直接输出
unset($res);
exec("ps -ef | grep " . $service . " | wc -l", $res);
print_r($res);//统计输出
}
query_process_num("httpd");
?>
输出如下:
→ ~/tmp/test $ ps -ef | grep httpd #命令行直接运行命令 0 92193 1 0 7:09下午 ?? 0:00.64 /usr/sbin/httpd -D FOREGROUND 70 92194 92193 0 7:09下午 ?? 0:00.00 /usr/sbin/httpd -D FOREGROUND 502 94092 70178 0 7:30下午 ttys002 0:00.01 grep httpd → ~/tmp/test $ php index.php #使用php查询 Array ( [0] => 0 92193 1 0 7:09下午 ?? 0:00.64 /usr/sbin/httpd -D FOREGROUND [1] => 70 92194 92193 0 7:09下午 ?? 0:00.00 /usr/sbin/httpd -D FOREGROUND [2] => 502 94109 94108 0 7:30下午 ttys002 0:00.00 sh -c ps -ef | grep httpd [3] => 502 94111 94109 0 7:30下午 ttys002 0:00.00 grep httpd ) Array ( [0] => 4 )
可以从上面的运行结果中就可以知道为什么要减2