I have a GUI program written in Java which outputs data to the command line using System.out.println
. The data is intended to be piped into another program. As an example, I'll pipe the program through head
:
$ java MyProgram | head -n10
I want my program to exit when the pipe is broken: in this case, this should happen after MyProgram
has printed out ten lines of text.
There is a similar question on this site, and the solution given there works fairly well; for example, I could have the following running in its own thread:
while(!System.out.checkError()) {
// sleep 100ms
}
System.exit(0);
The problem is that PrintStream.checkError()
seems to return true
only after you have tried to print to the stream and failed. For that reason, my program does not in fact exit until it has printed out eleven lines of text: the pipe is broken after the first ten, but System.out
continues to return true
until I try to pipe through the eleventh line.
Printing out extra 'junk' lines in order to trigger an error on the PrintStream
is out of the question, since the program on the right hand side of the pipe may be very sensitive to the data it receives.
Calling System.out.flush()
inside the loop has no effect on PrintStream.checkError()
, even though the source code for PrintStream
indicates that it ought to call the private ensureOpen
method in that class.
How can I reliably test whether System.out
is open without printing anything to it?
'Real world' example: suppose that I have some program consumer
that takes in command line input and does something with it. Certain pieces of input will call consumer
to fail silently. Since the input to consumer
is sometimes long and abstruse, I write a GUI program InputProvider
in Java where I can click buttons and have the corresponding commands printed out to stdout
. If I pipe the output of InputProvider
into consumer
, then I am able to control consumer
graphically.
Unfortunately, there seems to be no way for InputProvider
to notify the user when consumer
has shut down, except by attempting to write to consumer
and getting an exception of some kind.