Process Builder and Process in Java - how to execute a process with a timeout :? -
this question has answer here:
- java native process timeout 6 answers
i need execute external batch file in java specific timeout. means if batch execution take longer specified timeout, need cancel execution.
here sample code wrote:
public static void main(string[] args) throws ioexception, interruptedexception { processbuilder p = new processbuilder("c:\\wait.bat", "25"); // batch file execution take 25 seconds. final long l = system.currenttimemillis(); system.out.println("starting..." + (system.currenttimemillis() - l)); final process command = p.start(); system.out.println("started..." + (system.currenttimemillis() - l)); timer t = new timer(); t.schedule(new timertask() { @override public void run() { command.destroy(); } }, 5000); // kill process after 5 seconds (if it's not finished yet). int = command.waitfor(); t.cancel(); system.out.println("done..." + (system.currenttimemillis() - l)); system.out.println("result : " + i); system.out.println("really done..." + (system.currenttimemillis() - l)); }
the batch file "wait.bat" this:
@echo off echo starting process... @ping 127.0.0.1 -n 2 -w 1000 > nul @ping 127.0.0.1 -n %1% -w 1000> nul echo process finished succesfully @echo on
as see in code, batch file take 25 seconds finish (first line in main method) , timer destroy command after 5 seconds.
here output of code:
starting...0 started...0 done...5000 result : 1 done...5000 build successful (total time: 25 seconds)
as see in output, last line ("really done...") executed in 5th second application finished after 25 seconds.
my question : though called destroy method in timer, why jvm still waiting process finished ?
it bug in java's process.destroy()
implementation on windows. problem batch-script (or executing shell) killed, not kill own child processes (the ping here). thus, ping still running after .destroy()
, , after .waitfor()
. somehow vm still waits ping finish before finishing itself.
it seems there nothing can here java side kill ping reliably.
you may think using start
(in batch script or outside) invoke ping separate process.
(see previous discussion.)
or change unix-like operation system.
Comments
Post a Comment