我想使用Runtime.exec()
启动一个进程。然后我想知道(听)进程何时退出。另外,如果满足某些条件,我想手动停止该过程。
我现在的代码是:
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;
}
}
}
如代码所示,我的程序就像notepad.exe
一样,弹出一个窗口并立即返回。如何监听程序的状态,并等待它关闭,以及显式关闭它?
最佳答案
How can I listen to the status of the program, and wait until it is closed, as well as close it explicitly?
您可以使用Process#waitFor()
// cause this process to stop until process p is terminated
p.waitFor();
如JavaDoc说
The java.lang.Process.waitFor() method causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.
关于java - 在 Java 中启动、停止和监听进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28980378/