java代码 查询任务,如何在Windows中按端口查找PID并使用Java杀死找到的任务

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值