按照下面的代码,我试图通过端口获取tomcat进程ID并结束该进程。在CMD中,我得到了此命令,但用于Java的命令不起作用。我想纠正方法,请帮助我
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("netstat -aon | find /i \"listening\"");
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<OUTPUT>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</OUTPUT>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t) {
t.printStackTrace();
}
答案 0 :(得分:0)
如果您正在使用Windows,它将是这样。我没有针对linux进行过测试,但是我认为如果您检查评论代码,它应该可以工作。
public static void main(String[] args) throws IOException, InterruptedException {
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd /c netstat -ano | findstr 8080");
//for linux
//Process proc = rt.exec("/bin/bash -c netstat -ano |grep 8080");
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
String line = null;
System.out.println("<OUTPUT>");
if ((line = bufferedReader.readLine()) != null) {
int processIdString = line.lastIndexOf(" ");
String processId = line.substring(processIdString, line.length());
System.out.println("Your process Id to Kill : " + processId);
rt.exec("cmd /c Taskkill /PID" + processId + " /T /F");
//for linux
//rt.exec("/bin/bash -c kill -9 "+processId);
}
System.out.println("<OUTPUT>");
} catch (Exception e) {
System.out.println("Error Occured");
}
}