查看進程就是使用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
