Sunday, April 18, 2010

Java: execute program without blocking

A long while ago that I had done some Java programming... How to run a program from within Java in a decent manner. While looking around for some sample code, most solutions use the Process.waitFor() method to wait for the process to terminate. But that will usually block forever as process writes data to stdout or stderr and nothing reads that output.

One option is to use a separate thread to read stdout/stderr. I opted for an even simpler approach: temporary files:

execCommand = execCommand + " > " + stdoutFile.getFileName();
execCommand = execCommand + " 2> " + stderrFile.getFileName();
// command/program > stdout-temp 2> sterr-temp
Process p = Runtime.getRuntime().exec(execCommand, null, currDir);

int exitValue = 0;
boolean isRunning = true;
int waitSeconds = 30;
while(isRunning && (waitSeconds > 0)) {
try {
exitValue = p.exitValue();
isRunning = false;
} catch(IllegalThreadStateException e) {
// process is still running, wait 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// ignore
}
}
waitSeconds--;
}
if (isRunning) {
p.destroy();
exitValue = 9999;
}

stdoutFile.delete();
stderrFile.delete();


Authored by: Guy

No comments:

Post a Comment