user2426316
user2426316

Reputation: 7331

How can I wait for a subprocess to complete in a process in Java?

this is basically what I am trying to do: I created a Process that simulates the command line. Like this:

private Process getProcess() {
    ProcessBuilder builder = new ProcessBuilder("C:/Windows/System32/cmd.exe");
    Process p = null;
    try {
        p = builder.start();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return p;
} 

Now I can "feed" this process with commands:

BufferedWriter p_stdin = new BufferedWriter(
    new OutputStreamWriter(process.getOutputStream()));
try {
            p_stdin.write("dir"); // Just a sample command
            p_stdin.newLine();
            p_stdin.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to run " + fileName;
        }

What I now would like to do is wait for the command, that is the subprocess of my process, to complete. How can I do that? I know that I can wait for processes with the waitFor() method, but what about a subprocess??

Upvotes: 0

Views: 166

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200148

The dir command is not a subprocess, it is executed internal to cmd. However, this is not much relevant, anyway: from the perspective of Java any other command, which is launched in a subprocess, would behave the same.

To wait for the dir command to complete you must interpret the incoming stdout output from cmd and realize when the prompt was printed again. This is a quite brittle mechanism, though.

In any case, you currently don't consume cmd's stdout at all, which will cause it to block soon, never recovering.

Upvotes: 1

Related Questions