gpt4 book ai didi

java - 如何使用java获取linux中特定端口的进程信息

转载 作者:太空宇宙 更新时间:2023-11-04 12:23:56 30 4
gpt4 key购买 nike

我想找到在某个端口号上运行的进程processid。之后,我想使用 processid 终止那个 process。这就是我尝试的:

else if(OS.contains("linux")){
try{
JOptionPane.showMessageDialog(null, "in linux ");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("sudo netstat -nlp | grep :9090");

BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
String s = null;
StringBuilder sb=new StringBuilder();
while ((s = stdInput.readLine()) != null) {
sb.append(s);
System.out.println(s);
}
}

但是这个命令没有被执行。

那么我怎样才能得到在9090端口上运行的进程进程id呢?

最佳答案

试试这个运行代码,希望对你有帮助

else if (OS.contains("linux")) {
try {

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("netstat -nlp | grep :9090");

BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String s = null;
StringBuilder sb = new StringBuilder();
String sc = null;
while ((s = stdInput.readLine()) != null) {
if (s.contains("9090")) {
sb.append(s);
System.out.println(s);

String process = s.trim();
int index = process.lastIndexOf(" ");
int to = process.indexOf("/");

sc = s.substring(index, to);

}

rt.exec("kill -9 " + sc);
}}

关于java - 如何使用java获取linux中特定端口的进程信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45251449/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com