Here is a section of code in my Java program (in the main thread) :
int bufSize = 4096; // 4k buffer.
byte[] buffer = new byte[bufSize];
int bytesAvailable, bytesRead;
try {
while ( true ) {
bytesAvailable = System.in.available(); // seems may throw IOException if InputStream is closed.
if ( bytesAvailable > 0 ) {
if ( bytesAvailable > bufSize ) {
bytesAvailable = bufSize;
}
// The following statement seems should not block.
bytesRead = System.in.read(buffer, 0, bytesAvailable);
if ( bytesRead == -1 ) {
myOutputStream.close();
System.out.println("NonBlockingReadTest : return by EOF.");
return;
}
myOutputStream.write(buffer, 0, bytesRead);
myOutputStream.flush();
} else if ( bytesAvailable == 0 ) {
// Nothing to do, just loop over.
} else {
// Error ! Should not be here !
}
}
} catch (IOException e) {
.....
The program runs OK. It just reads (in a non-blocking way) some input from stdin and then write the input to a file. I have used "System.in.available()" so that the "System.in.read(buffer, 0, bytesAvailable)" statement would not block.
However, I could not terminate the program by typing "ctrl-D" in the keyboard. I could only terminate it by "ctrl-C" and I think that's not a graceful way. It seems that the "bytesRead == -1" condition is never true.
Is that any modification I could do so that the program could be terminated by "ctrl-D". Any idea, thanks.