multithreading - java thread periodically kills a process -
i have java class kicks off a script via
process proc = runtime.getruntime().exec(" run script"); for specific reasons pretty runs time. if script dies whatever reason java class starts up.
now i'm needing kill process every often. decided kick off thread sit , wait specific time, , kill process. java main class, or whatever, still see process die , start up.
i don't know how thread see process , subsequently kill every often. suggestions on how create thread? note, haven't had work threads in little while, i'm little rusty.
simple pseudo code of class basic idea of i'm doing:
class myclass{ process mproc; main(args){ do{ try{ mproc = runtime.getruntime().exec("cmd /c myscript"); mproc.destroy(); } catch(exception e){ log(e); } } while(true);
i don't know how thread see process , subsequently kill every often.
this not easy of java 6. process class has waitfor() method not take timeout tragic given internally calling wait() -- @ least in unixprocess.
what can do, of hack synchronize on process , call wait(timeoutmillis) yourself. like:
process proc = new processbuilder().command(commandargs).start(); long startmillis = system.currenttimemillis(); synchronized (proc) { proc.wait(sometimeoutmillis); } long diff = system.currenttimemillis() - startmillis; // if here without being interrupted , delay time more // sometimeoutmillis, process should still running if (diff >= sometimeoutmillis) { proc.destroy(); } the issue there race condition , if process finishes before synchronize on proc going wait ever. solution proc.waitfor() in 1 thread , interrupt in thread once timeout expires.
process proc = new processbuilder().command(commandargs).start(); try { // interrupted thread int errorcode = proc.waitfor(); } catch (interruptedexception e) { // pattern re-interrupt thread thread.currentthread().interrupt(); // our timeout must have expired need kill process proc.destroy(); } // maybe stop timeout thread here another option use proc.exitvalue() allows test see if process executed. unfortunately instead of returning -1 or throws illegalthreadstateexception if has not finished.
Comments
Post a Comment