如何使用其他Java程序停止运行程序
我一直在实现一个程序来编译和运行其他应用程序。 当我的应用程序发现存在例如无限循环的问题时,我想知道是否有办法终止程序。 我试图使用process.Destroy()但它杀死CMD而不是那个有无限循环的实际程序…
非常感谢您的帮助。
这是我的代码的一部分:
synchronized (pro) { pro.wait(30000); } try{ pro.exitValue(); }catch (IllegalThreadStateException ex) { pro.destroy(); timeLimitExceededflag = true; System.out.println("NOT FINISHED123"); System.exit(0); } }
基本上我正在使用processBuilder来调用cmd。 此代码终止CMD,但如果它运行的程序具有无限循环,则应用程序仍将运行,这会影响我的服务器性能。
我建议使用以下解决方案:
- 使用指定的标题启动您的程序
- 使用“tasklist”命令获取进程的PID。 需要CSV解析器。 我相信有很多可用的,比如org.apache.commons.csv.CSVParser等:)
- 使用PID通过“taskkill”命令终止进程。
以下是可能有用的代码的一部分:
public static final String NL = System.getProperty("line.separator", "\n"); public int command(String... cmd) throws Exception { return command(null, cmd); } public int command(T out, String... cmd) throws Exception { try { final ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); final Process proc = pb.start(); final BufferedReader rd = new BufferedReader(new InputStreamReader(proc.getInputStream())); for (;;) { final String line = rd.readLine(); if (line == null) { break; } if (out != null) { out.append(line); out.append(NL); } } return proc.waitFor(); } catch (InterruptedException e) { throw new IOException(e); } } public void startProcessWithTitle(String pathToExe, String title) throws Exception { command("cmd.exe", "/C", "start", '"' + pathToExe + '"', '"' + title + '"', ..cmd.params..); } public int findProcessByTitle(String title) throws Exception { final StringBuilder list = new StringBuilder(); if (command(list, "tasklist", "/V", "/FO", "csv") != 0) { throw new RuntimeException("Cannot get tasklist. " + list.toString()); } final CSVReader csv = new CSVReader(new StringReader(list.toString()), ',', true, "WindowsOS.findProcessByTitle"); csv.readHeaders(true); // headers int pidIndex = csv.getHeaderIndex("PID"); int titleIndex = csv.getHeaderIndex("Window Title"); while (csv.nextLine()) { final String ttl = csv.getString(titleIndex, true); if (ttl.contains(title)) { return csv.getInt(pidIndex); } } Utils.close(csv); return -1; } public boolean killProcess(int pid) throws Exception { return command("taskkill", "/T", "/F", "/PID", Integer.toString(pid)) == 0; }