I want to start a process with Runtime.exec()
. Then I want to know (listen) when the process exits. Also, I want to manually stop the process if some condition met.
The code I have now is:
public class ProcessManager extends Thread{
private static ProcessManager manager;
Process process;
private ProcessManager(){
}
public static ProcessManager getInstance(){
if(manager==null){
manager=new ProcessManager();
}
return manager;
}
public void run(){
Runtime runtime = Runtime.getRuntime();
process = runtime.exec("c:\\windows\\system32\\notepad.exe");
//cleanup();
}
public void cleanup(){
//I want to do stuffs until the program really ends;
}
//called to manually stop the process
public void stopProcess(){
if(process!=null){
//TODO: stop the process;
}
}
}
As shown in the code, my program is like notepad.exe
, which pop up a window and immediately returns. How can I listen to the status of the program, and wait until it is closed, as well as close it explicitly?
I would not recommend using Runtime.exec() directly. It is not as straightforward as it might seem. Nice article "When Runtime.exec() won't" describes these pitfalls in details. For example simple code with waitFor():
will produce no output and hangs, because in general you need to provide handling of input, output and error streams in separate threads.
Instead you may use Apache Commons Exec library that will handle it for you:
Below is more complex example of asynchronous process terminated manually:
You can use
Process#waitFor()
As JavaDoc says