启动,停止和收听Java中的进程 [英] Start, stop and listen to a process in Java

查看:107
本文介绍了启动,停止和收听Java中的进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Runtime.exec()开始一个过程.然后我想知道(听)该进程何时退出.另外,如果满足某些条件,我想手动停止该过程.

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.

我现在拥有的代码是:

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,它会弹出一个窗口并立即返回.我该如何监听程序的状态,并等待它关闭并显式关闭它?

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?

推荐答案

我该如何收听程序的状态,并等待直到 关闭,以及显式关闭?

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

java.lang.Process.waitFor()方法使当前线程 如有必要,请等待,直到该流程表示的流程为止 对象已终止.如果 子进程已经终止.如果子流程还没有 终止,调用线程将被阻塞,直到子进程 退出.

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中的进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆