Java executing commands in Operating System
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:
Thread t = new Thread(new Runnable() {
public void run() {
// stuff your code here
}
});
t.run();
while (t.isAlive()) {
t.join(1000); // wait for one second
System.out.println("still waiting");
}
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.
You could spawn a new thread before starting the process.
The new thread would be responsible for printing out "Process is going on..." or whatever is needed.
After p.waitFor() finishes, the main thread that launched the process would indicate to the new thread that it should stop running.
You could spawn a new thread and do the wait in the thread, checking periodically from the master thread via a shared variable whether the waiting thread had completed.
精彩评论