How find PID by port in windows and kill found tasks using java

江枫思渺然 提交于 2019-12-11 03:59:51

问题


I need kill process in java code by process port. I can do it manually in cmd like:

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

In java I could execute cmd command like:

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

But I don't know how get PID as output of netstat and transfer it to the "taskkill" command. Could anyone suggest me?


回答1:


You can execute the ProcessBuilder and get the response from its Input Stream.

Sample Code :

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);
    }

The "-a" argument for netstat causes the Process Builder to wait indefinitely. You will need to remove that. Additionally if you required to get the Error Stream then the following can be added.

printProcessStream(process.getErrorStream());

Once you get the response stream, you can parse the data and identify the PID to kill. Subsequently you can use the similar logic but changing the command, instead of netstat you can use the command "kill -9 $PID" to finally kill the process.



来源:https://stackoverflow.com/questions/32247743/how-find-pid-by-port-in-windows-and-kill-found-tasks-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!