【问题标题】:Java, windows: Get process name of given PIDJava,Windows:获取给定PID的进程名称
【发布时间】:2014-07-11 11:19:03
【问题描述】:

在 Windows 上运行。

我需要从我的程序中了解哪些进程(如 Skype)正在端口 :80 上运行。

我应该能够通过端口:80 获得进程的PID

netstat -o -n -a | findstr 0.0:80.

从 Java 中获取具有给定 PID 的进程名称的最佳方法是什么?

如果有任何方法可以从 Java 中获取在端口 :80 上运行的进程的名称,我也希望这样做。

我需要这个的原因是我的应用程序启动了一个使用端口:80 的码头网络服务器。我想警告用户另一个服务已经在运行端口:80,以防万一。

【问题讨论】:

  • 您是在 Windows 还是 Linux 上运行?

标签: java process jetty port pid


【解决方案1】:

所以我使用两个 Process.一种用于获取 PID,一种用于获取名称。

这里是:

private String getPIDRunningOnPort80() {
        String cmd = "cmd /c netstat -o -n -a | findstr 0.0:80";

        Runtime rt = Runtime.getRuntime();
        Process p = null;
        try {
            p = rt.exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }

        StringBuffer sbInput = new StringBuffer();
        BufferedReader brInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader brError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        String line;
        try {
            while ((line = brError.readLine()) != null) {
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            while ((line = brInput.readLine()) != null) {
                sbInput.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        p.destroy();

        String resultString = sbInput.toString();
        resultString = resultString.substring(resultString.lastIndexOf(" ", resultString.length())).replace("\n", "");
        return resultString;
    }



private String getProcessNameFromPID(String pid) {
    Process p = null;
    try {
        p = Runtime.getRuntime().exec("tasklist");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    StringBuffer sbInput = new StringBuffer();
    BufferedReader brInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    String foundLine = "UNKNOWN";
    try {
        while ((line = brInput.readLine()) != null) {
            if (line.contains(pid)){
                foundLine = line; 
            }
            System.out.println(line);
            sbInput.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        p.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    p.destroy();

    String result = foundLine.substring(0, foundLine.indexOf(" "));



    return result;
}

【讨论】:

    猜你喜欢
    • 2011-04-28
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2016-01-31
    • 2023-04-10
    相关资源
    最近更新 更多