2011-09-21 240 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>'; 
}