如何在Windows中按端口查找PID并使用Java杀死找到的任务
我需要通过进程端口杀死Java代码中的进程. 我可以在cmd中手动完成操作,例如:
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
在Java中,我可以执行以下cmd命令:
In java I could execute cmd command like:
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "netstat -a -n -o | findstr :6543");
但是我不知道如何将PID作为netstat的输出并将其传输到"taskkill"命令.有人可以建议我吗?
But I don't know how get PID as output of netstat and transfer it to the "taskkill" command. Could anyone suggest me?
您可以执行ProcessBuilder并从其输入流中获取响应.
You can execute the ProcessBuilder and get the response from its Input Stream.
示例代码:
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"参数使Process Builder无限期等待.您将需要删除它.此外,如果需要获取错误流,则可以添加以下内容.
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());
一旦获得响应流,就可以解析数据并标识要杀死的PID.随后,您可以使用类似的逻辑,但是要更改命令,而不是netstat,您可以使用命令"kill -9 $ PID"最终终止该进程.
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.