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?
解决方案
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.