如何在Windows中通过端口查找PID并使用java杀死找到的任务

2024-02-13

我需要通过进程端口在java代码中杀死进程。 我可以在 cmd 中手动执行此操作,例如:

C:\>netstat -a -n -o | findstr :6543
TCP    0.0.0.0:6543           0.0.0.0:0              LISTENING       1145
TCP    [::]:6543              [::]:0                 LISTENING       1145

C:\>taskkill /F /PID 1145

在java中我可以执行cmd命令,例如:

ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "netstat -a -n -o | findstr :6543");

但我不知道如何获取 PID 作为 netstat 的输出并将其传输到“taskkill”命令。有人可以建议我吗?


您可以执行 ProcessBuilder 并从其输入流获取响应。

示例代码:

public static void main(String[] args) throws IOException, InterruptedException
    {
    ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/C", "netstat -n -o | findstr :6129");
    Process process = builder.start();
    process.waitFor();
    printProcessStream(process.getInputStream());
    }

    private static void printProcessStream(InputStream inputStream) throws IOException
    {
    int bytesRead = -1;
    byte[] bytes = new byte[1024];
    String output = "";
    while((bytesRead = inputStream.read(bytes)) > -1){
        output = output + new String(bytes, 0, bytesRead);
    }
    System.out.println(" The netstat command response is \r\n"+output);
    }

netstat 的“-a”参数会导致进程生成器无限期等待。您需要将其删除。此外,如果您需要获取错误流,则可以添加以下内容。

printProcessStream(process.getErrorStream());

一旦获得响应流,您就可以解析数据并识别要杀死的 PID。随后,您可以使用类似的逻辑,但更改命令,而不是 netstat,您可以使用命令“kill -9 $PID”来最终终止进程。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Windows中通过端口查找PID并使用java杀死找到的任务 的相关文章

随机推荐