Reading Output from a Command

try { // Execute command String command = "ls"; Process child = Runtime.getRuntime().exec(command); // Get the input stream and read from it InputStream in = child.getInputStream(); int c; while ((c = in.read()) != -1) { process((char)c); } in.close(); } catch (IOException e) { }

Comments

21 Jun 2010 - 4:33pm by Chauhan (not verified)

This was very handy to know. One point of confusion was naming: the 'InputStream' of the parent process contains the output ('stdout' on UNIX) of the child process.

Also note, any Process.waitFor() method call (used to get the exit value of the process) must be done *after* the while loop above has a chance to empty the process' stdout buffers. Otherwise, the process can deadlock on certain platforms with limited stdout buffers. This may also apply to stderr.

On AIX, the stdout buffer is apparently about 100 KB. If a Process.waitFor() call is made above the code that reads stdout and stderr, a process which generates more than 100 KB on stdout deadlocks and never returns control to waitFor(). At least that's my experience until I moved Process.waitFor() below the while loops that emptied stdout and stderr

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.