Athanasia Notta
Athanasia Notta

Reputation: 99

Java running bash command while feeding it input and getting output

I've got to write down some java code that runs an external process. This process gets an input line from stdin and gives an output line on stdout.

The code I wrote is as follows

try
{            
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("./" + args[0]);
    Process proc2 = rt.exec(c);
    int exitVal = proc2.exitValue();
    System.out.println("Process exitValue: " + exitVal);
} 
catch (Throwable t){
}

Where args[0] is the external process and c is the input (String) I need to feed to the process. If it was running correctly, I would get an exitVal=0, instead I get nothing. Also, what I really want to print is the output of the external process (which would be "6" in the given example).

Upvotes: 0

Views: 1522

Answers (3)

wytten
wytten

Reputation: 3000

You can feed the program input with '<' redirection:

{
  Process p = Runtime.getRuntime().exec("wc < pom.xml");
  p.waitFor();
  System.out.println(p.exitValue());
  BufferedReader bri = new BufferedReader
    (new InputStreamReader(p.getInputStream()));
  String line;
  while ((line = bri.readLine()) != null) {
    System.out.println(line);
  }
  bri.close();
}

Upvotes: 0

wds
wds

Reputation: 32283

You must use getInputStream() and getOutputStream() on the process to communicate it, see the javadocs.

If you do not read all data from the process, it might hang and even deadlock. For a short introduction on common problems, see this blog post. At the very least, you should be reading all data from the process output.

Upvotes: 2

AlexR
AlexR

Reputation: 115328

You cannot "get nothing". Method exitValue() returns primitive type, therefore it even cannot be null. But this method can stuck however. This happens because your process is still running.

Is is possible that it is running because you did not "feed" it? In this case the only thing you have to do is to call proc2.getOutputStream() and write what you need to this stream. If you want to read the process' output use proc2.getInputStream() and read from the stream.

BTW, take a look on ProcessBuilder. It provides better, more "object oriented" API thant simple Runtime.exec().

Upvotes: 0

Related Questions