4

I have a java application taking data from stdin and writing results to stdout. Like this:

app1 | java_app | app2

The amount of data moved through the pipe is large and takes a long time (hours and days is not uncommon or unexpected).

Its seems that if app1 dies, and closes its end of the pipe, I receive a pipe related exception. However is app2 dies, and closes its end of the pipe I do not receive an exception. This means that java_app continues on consuming input, which will never generate any useful output, running for hours or days.

The difference in pipe exception reporting seems to stem from System.in being an InputStream, while System.out is a PrintStream and PrintStreams swallow up any errors. I know you can get the error state from a PrintStream by using stream.checkError() - but using that everywhere is clunky (and forces a flush of your output stream.) I 'm happy to forgo the bulk of functionality of PrintStream to get better error reporting.

Is there another way to get access to stdout that isn't wrapped in a PrintStream, but instead a nicer OutputStream?

Mandar Pandit
  • 2,171
  • 5
  • 36
  • 58
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
  • 1
    possible duplicate of [How do I get java to exit when piped to head](http://stackoverflow.com/questions/11695500/how-do-i-get-java-to-exit-when-piped-to-head) – Raedwald Jun 16 '14 at 07:08
  • 1
    @Raedwald - IMO its not a dupe - but its related. The top answer there wasn't appropriate for this example (as it involved the use of `checkError()`). The second answer is an alternate approach that links back to this question. (i.e. now that I have a solution I added the alternative option to the other.) – Michael Anderson Jun 16 '14 at 07:34
  • 1
    Using 2 different approaches to answer one question does not give you 2 different questions. – Raedwald Jun 16 '14 at 11:46
  • I wrote the other question, and in my opinion, they're basically the same. I used the example of piping output into `head`, but that's a specific instance of the general issue of the output pipe being closed and wanting to detect and handle that case somehow. – onlynone Jun 17 '14 at 20:57
  • I've rolled the additional info here into part of my answer on the linked question. So I'll close this one. – Michael Anderson Sep 30 '14 at 00:34

1 Answers1

1

Turns out one of my colleagues found a nice way to do this.

OutputStream stream = new FileOutputStream(FileDescriptor.out);
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187