2011-09-21 75 views
1

我試圖做一個服務器管理器和這裏是我到目前爲止有:解析grep的輸出

<?php 
$COMMAND = shell_exec('ps ax --format command | grep skulltag'); 
$arr = explode("./",$COMMAND); 
$text = shell_exec('pgrep -u doom'); 
$arrtext = preg_split('/\s+/', $text); 
for($i = 1; $i < count($arr); $i++) { 
    echo $i,". PROCESS ID ",$arrtext[$i]," Command issued: ",$arr[$i]; 
    echo '<br>'; 
} 
?> 

正如你所看到的,我分開$命令字符串以./(文件執行)。然而,由於某種原因,在列表的末尾有這樣的:

sh -c ps ax --format command | grep skulltag grep skulltag 

下面是引用完整的輸出:

  1. 進程ID 4793命令發出:skulltag服務器
  2. 過程ID 4956發出的命令:skulltag-server -port 13000
  3. 進程ID 4958發出的命令:skulltag-server -port 13001 sh -c ps ax --format command | grep的skulltag grep的skulltag

什麼是擺脫該行的最簡單,最有效的方式,我會怎麼做呢?謝謝。

+5

如果我理解你的要求,規範的解決方案是使用不匹配自身的模式,例如'grep [s] kulltag'。 – tripleee

+2

「出於某種原因」 - 這是因爲您正在運行的命令正在運行,所以它顯示在正在運行的進程列表中。 – Quentin

+1

如果你有'pgrep',你爲什麼要重新實現它? – tripleee

回答

1

我的快速和骯髒的解決方案是將| grep -v grep附加到該命令。

+1

修復正則表達式更優雅。 – tripleee

2

更改此:

ps ax --format command | grep skulltag 

向該:

ps ax --format command | grep [s]kulltag 

這樣,grep命令本身包含字符串 '[s]的kultag',這不是由grep的正則表達式匹配'[S] kultag'。

另外,兩點建議:1.不保證你的初始ps | grep和你以後的pgrep會排隊。相反,使用單個p纖ep:

pgrep -afl skulltag 

和2你的for循環從1開始,這將跳過過程中ARR [0]。

你的PHP可以改寫這樣的事:

$processes = explode("\n", shell_exec('pgrep -afl skulltag')); 
foreach($processes as $i => $process) { 
    ($pid, $command) = explode(' ',$process,2); 
    echo $i+1,". PROCESS ID ",$pid," Command issued: ",$command; 
    echo '<br>'; 
}