[英]How to Stop a Running a Program Using Other Java Program
I have been implementing a program to compile and run other applications. 我一直在执行一个程序来编译和运行其他应用程序。 I was wondering if there is a way to terminate a program when my application discovers that there is an issue eg infinite loop.
我想知道当我的应用程序发现存在无限循环之类的问题时是否有终止程序的方法。 I tried to using process.Destroy() but it kills the CMD not that actual program that has infinite loop...
我尝试使用process.Destroy(),但它杀死了CMD而不是具有无限循环的实际程序...
Your help is really appreciated. 非常感谢您的帮助。
Here is a part of my code: 这是我的代码的一部分:
synchronized (pro) {
pro.wait(30000);
}
try{
pro.exitValue();
}catch (IllegalThreadStateException ex)
{
pro.destroy();
timeLimitExceededflag = true;
System.out.println("NOT FINISHED123");
System.exit(0);
}
}
Basically I am making my application to invoke the cmd using a processBuilder. 基本上,我正在使我的应用程序使用processBuilder来调用cmd。 This code terminates the CMD but if it runs a program that has an infinite loop that application will be still running which affects my servers performance.
该代码终止了CMD,但如果它运行的程序具有无限循环,则该应用程序仍将运行,这会影响我的服务器性能。
I'd suggest to use the following solution: 我建议使用以下解决方案:
Here is some part of code which may be useful: 这是一些可能有用的代码:
public static final String NL = System.getProperty("line.separator", "\n");
public <T extends Appendable> int command(String... cmd) throws Exception {
return command(null, cmd);
}
public <T extends Appendable> 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.