开发者

How do I wait for a process started by Runtime.exec() to finish?

I have the next code:

Process p = Runtime.getRuntime().exec(args);

and I want my program to wait for the Runtime.getRuntime().exec(args); to finish cau开发者_如何转开发se it last 2-3sec and then to continue.

Ideas?


use Process.waitFor():

Process p = Runtime.getRuntime().exec(args);
int status = p.waitFor();

From JavaDoc:

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.


Here is a sample code:

Process proc = Runtime.getRuntime().exec(ANonJava.exe@);
InputStream in = proc.getInputStream();
byte buff[] = new byte[1024];
int cbRead;

try {
    while ((cbRead = in.read(buff)) != -1) {
        // Use the output of the process...
    }
} catch (IOException e) {
    // Insert code to handle exceptions that occur
    // when reading the process output
}

// No more output was available from the process, so...

// Ensure that the process completes
try {
    proc.waitFor();
} catch (InterruptedException) {
    // Handle exception that could occur when waiting
    // for a spawned process to terminate
}

// Then examine the process exit code
if (proc.exitValue() == 1) {
    // Use the exit value...
}

You can find more on this site: http://docs.rinet.ru/JWP/ch14.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜