0

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??

user2426316
  • 7,131
  • 20
  • 52
  • 83
  • Does [my answer to a similar question](http://stackoverflow.com/a/3644288/) help? (It uses `/bin/bash`, but you should be able to replace that with `cmd.exe`.) – Luke Woodward Sep 19 '13 at 11:35

1 Answers1

1

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436