I'm writing a command-line utility in Java that either consumes stdin or writes to stdout depending on whether there is data available on stdin using System.in.available():
public class MyUtility {
public static void main(String args[]) {
if(System.in.available() > 0)
consumeFromStdin();
else
produceToStdout();
}
// ...
}
I'm using the System.in.available() check to avoid using command-line parameters, to make the mode-of-operation dependent on how it is used in the shell (i.e., java MyUtility | more versus echo testing | java MyUtility).
So far, this is working well from the Mac command-line; stdin availability has always existed by the time System.in.available() is called. My question is: could it be possible that, even when calling the utility with
java MyUtility < input.txt
System.in.available() here may return 0 ?
Of course, I would like this to work for all JVM implementations, shells, and OSs. Does Windows, Mac, and Linux offer different (any?) guarantees on stdin data availability by the time processes are spawned? And, even if the OS guarantees data availability, does the JVM have any say on guaranteeing this data as well? Do shells (i.e., ksh, csh, PowerShell, etc.) play a role?
Inter-process communication exists independently of the shell. Standard in and standard out are operating-system mechanisms which the shell uses, but does not create. Processes that are not shells use them all the time.
I do not know enough about the specification for the available() method, but if you perform a quick check on Windows and it works, the rest of the OSes being mostly UNIX-style, there is, I think, a high likelihood that it will work everywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With