I have two different commands (on an external EXE file) represented by two String array command1
and command2
. I want to run those two sequentially within the same thread. To be specific, the first command is executed for 10 minutes. If it takes longer time, terminate it and run the second command. Here is what I am doing.
public class MyRunnable implements Runnable {
private Process proc;
private String[] command1;
private String[] command2;
public MyRunnable (String[] command1, String[] command2) {
this.command1 = command1;
this.command2 = command2;
}
public void run() {
try {
proc = Runtime.getRuntime().exec(command1);
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
errorGobbler.start();
outputGobbler.start();
exitCode = proc.waitFor(10, TimeUnit.MINUTES);
if (exitCode)
System.out.println("Model " + modelPath + ": SUCCESSFULLY!");
else {
System.out.println("Model " + modelPath + ": TIMED OUT!");
proc = Runtime.getRuntime().exec(command2);
StreamGobbler errorGobbler1 = new StreamGobbler(proc.getErrorStream(), "ERROR");
StreamGobbler outputGobbler1 = new StreamGobbler(proc.getInputStream(), "OUTPUT");
errorGobbler1.start();
outputGobbler1.start();
proc.waitFor(10, TimeUnit.MINUTES);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
proc.destroy();
}
}
}
The StreamGobbler
class I implemented exactly the same as here www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html to avoid deadlocks. Generally, its role is to let another thread handle the output and error streams of the proc
object.
I am not sure whether it is appropriate to assign two different sub-processes to the same Process object as above. I observe that the process with command1 still runs even after calling the proc.waitFor(10, TimeUnit.MINUTES)
, which creates a lot of processes on my computer after a while. How to terminate the process of the first command ? I am using Java 1.8 on CentOS 7.
Thanks in advance.
In your if
if you reach the else
statement the process has exceeded the timeout, so before you assign the new process to proc
you must first terminate the previous one. There are two methods for that proc.destroy()
and proc.destroyForcibly()
add any of the in you else
statement before proc = Runtime.getRuntime().exec(command2);
and it should be fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.