Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is going through getErrorStream() necessary to run a process?

Tags:

java

process

I am executing a process using the Process class. Going through the error stream seems to be necessary to execute the process successfully. Why is going through the error stream necessary for the process to run correctly? Is there something I am doing wrong?

Process wkstdin = Runtime.getRuntime().exec(command);
BufferedWriter wkstdin_writer = new BufferedWriter(
            new OutputStreamWriter(wkstdin.getOutputStream()));
//write data

Necessary Part of the Code:

BufferedReader input = new BufferedReader(new InputStreamReader(
            wkstdin.getErrorStream()));
String ch;
while ((ch = input.readLine()) != null)
{
  System.out.println(ch);
}
like image 607
KrispyDonuts Avatar asked Feb 21 '23 05:02

KrispyDonuts


1 Answers

When the process writes to stderr the output goes to a fixed-size buffer. If the buffer fills up then the process blocks until there is room for the remaining output in the buffer. So if the buffer doesn't empty then the process will hang.

Also if something goes wrong with the process you'd like to know about it, the error stream may contain actual useful information.

Some suggestions:

  • Naming a String ch seems misleading, since ch is usually used for chars.
  • I like to put the code that reads from stderr in a dedicated worker thread. That way switching between reading the input stream and the error stream happens automatically without my having to allow for it.
like image 113
Nathan Hughes Avatar answered Apr 05 '23 21:04

Nathan Hughes