I have a Java program that executes specific commands into the OS. Am also using Process.waitfor() as showing in the code below to indicates if the execution completed successfully or failed.
My question is, is there any other way to avoid using process.waitfor(), Is there a way to use while loop and perform certain action until the process is completed?
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmdFull);
BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inStreamLine = null;
String inStreamLinebyLine=null;
while((inStreamLine = inStream.readLine()) == null) {
inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine;
}
try {
rc = p.waitFor();
} catch (InterruptedException intexc) {
System.out.println("Interrupted Exception on waitFor: " +
intexc.getMessage());
}
Waht I wish to do, is something like this
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmdFull);
BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inStreamLine = null;
String inStreamLinebyLine=null;
while((inStreamLine = inStream.readLine()) == null) {
inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine;
}
try {
while ((rc = p.waitFor()) == true ) { // This is made up, I don't even think it would work
System.out.println('Process is going on...');
}
} catch (InterruptedException intexc) {
System.out.println("Interrupted Exception on waitFor: " +
intexc.getMessage());
}
Thanks,
Maybe something like this would work. Create a Thread as @tschaible suggested, then do a join on a that thread with a timeout (which is the part you made up in your code). It would look something like this:
What this does is launch the code as a separate thread and then test if the tread finished every one second. The while loop should end when thread finishes and is no longer alive. You might have to check for InterruptedException but I can’t test that now.
Hope this sends you in the right direction.