java - Call Runtime.getRuntime.exec(commands) twice on the same Process object -
i have 2 different commands (on external exe file) represented 2 string array command1 , command2. want run 2 sequentially within same thread. specific, first command executed 10 minutes. if takes longer time, terminate , run second command. here 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(); } { proc.destroy(); } } } the streamgobbler class implemented same here www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html avoid deadlocks. generally, role let thread handle output , error streams of proc object.
i not sure whether appropriate assign 2 different sub-processes same process object above. observe process command1 still runs after calling proc.waitfor(10, timeunit.minutes), creates lot of processes on computer after while. how terminate process of first command ? using java 1.8 on centos 7.
thanks in advance.
in if if reach else statement process has exceeded timeout, before assign new process proc must first terminate previous one. there 2 methods proc.destroy() , proc.destroyforcibly()add of in else statement before proc = runtime.getruntime().exec(command2); , should fine.
Comments
Post a Comment