使用java

时间:2015-06-28 11:23:16

标签: java linux grep runtime

我想使用top命令获取进程信息。我有下面的代码,但它不工作,它只是存在没有任何输出的程序。我的目标是获取进程名称,进程ID和内存使用情况,但这是后面的部分。目前,我使用top在Java中使用grep命令获取流程信息。

public void getProcessInfo(String processName) {
    Runtime rt = Runtime.getRuntime();
    try {
        String[] cmd = { "/bin/sh", "-c", "top | grep " + processName };
        Process proc = rt.exec(cmd);
        InputStream stdin = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);       
        }
    } catch (Exception e) {
        e.printStackTrace(e);
    }
}

2 个答案:

答案 0 :(得分:2)

之前已经多次询问过这个问题:

在正常模式下,top命令输出到stdout,这就是为什么你不能简单地将其输出管道输出到另一个CLI实用程序中。相反,你必须将命令切换到"批处理模式"使用-b标志。此外,如果要处理结果,则必须将迭代次数限制为单个(在非交互模式下无法进一步迭代):

top -b -n 1 | grep "whatever"

这在命令手册页中有记录:man top

玩得开心!

答案 1 :(得分:1)

Runtime.exec已过时。请改用ProcessBuilder

通过完全避免使用grep或任何管道,您可以大大简化您的任务。有Java时谁需要grep?

在arkascha的回答基础上,您可以这样做:

String processLine = null;

ProcessBuilder builder = new ProcessBuilder("top", "-b", "-n", "1");
Process proc = builder.start();

try (BufferedReader stdin = new BufferedReader(
    new InputStreamReader(proc.getInputStream()))) {

    String line;
    while ((line = stdin.readLine()) != null) {
        if (line.contains(processName)) {   // No need for grep
            processLine = line;
            break;
        }
    }
}

您可能希望跳过摘要信息和标题行:

String processLine = null;

ProcessBuilder builder = new ProcessBuilder("top", "-b", "-n", "1");
Process proc = builder.start();

try (BufferedReader stdin = new BufferedReader(
    new InputStreamReader(proc.getInputStream()))) {

    String line;

    // Blank line indicates end of summary.
    while ((line = stdin.readLine()) != null) {
        if (line.isEmpty()) {
            break;
        }
    }

    // Skip header line.
    if (line != null) {
        line = stdin.readLine();
    }

    if (line != null) {
        while ((line = stdin.readLine()) != null) {
            if (line.contains(processName)) {   // No need for grep
                processLine = line;
                break;
            }
        }
    }
}