Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect I/O of subprocess in Java (why doesn't ProcessBuilder.inheritIO() work?)

Tags:

java

io

process

I'm launching a process in the following way.

try {
    final Process mvnProcess = new ProcessBuilder("cmd", "/c", "mvn", "--version")
            .directory(new File(System.getProperty("user.dir")))
            .inheritIO()
            .start();
    System.exit(mvnProcess.waitFor());
} catch (final IOException ex) {
    System.err.format(IO_EXCEPTION);
    System.exit(1);
} catch (final InterruptedException ex) {
    System.err.format(INTERRUPTED_EXCEPTION);
    System.exit(1);
}

Since I invoke inheritIO() I was expecting the sub-process's output on the console, but nothing appears. What am I missing here?

Edit: I know that I can use mvnProcess.getInputStream() and read the process's output explicitly, writing it to the console (or where-ever) in a loop. I don't like this solution however, since the loop will block my thread. inheritIO() looked promising, but apparently I don't understand how it works. I was hoping someone here could shed some light on this.

like image 470
Rinke Avatar asked Jul 08 '13 11:07

Rinke


2 Answers

Maybe it is an option the read it from the subprocess:

Add this code after start() and you will have it printed to stdout:

    InputStream is = mvnProcess.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null)
    {
        System.out.println(line);
    }
like image 107
t7bdh3hdhb Avatar answered Nov 11 '22 18:11

t7bdh3hdhb


You can use the .redirectError(Redirect.INHERIT). It sets the source and destination for sub process standard I/O to be the same as those of the current Java process.

like image 44
Shreyansh Patni Avatar answered Nov 11 '22 18:11

Shreyansh Patni