echo "some spaces"should the the argv passed to exec() contain two words or three, and should the output be
some spacesor
"some spaces"
See also Q2, Q3
ls *produces the output
ls: *: No such file or directory
java P1 < testfileEOF means just what the name implies: the end of the file. If the input comes directly from the keyboard, you can simulate an EOF condition by typing control-D (type 'd' while holding down the control key). On Windows, use control-Z instead. When it detects eof-of-file, readLine() returns null (that's the null-pointer value null not a string of length zero). Your program should not terminate on an empty command line; instead it should do nothing but print another prompt. See Q3.
If you try to echo the output and error streams before waiting for the process to terminate, you have to read from one before the other. Suppose you first read from the error stream and the command you're running is trying to write to its output stream. Your thread will be blocked waiting to read data from the error stream while there's nothing there to read. Your read() call cannot return null (meaning there's nothing more to read) until the command finishes, since there's no way to guarantee there will be no error output until the command finishes running. But the command cannot terminate until it successfully writes its output to its output stream, and it cannot do that until you read it. Once again, you have deadlock. Of course, if you decide to read from the output stream first, you will deadlock with a command that wants to write a lot of data to its error stream.
The reason your tests seem to work ok is that there is a certain amount of buffering built into the streams (that is, memory arrays where the data sits after the command has written it but before your program reads it). In your test, the command writes its output into the stream buffers and terminates; then your program notices it has terminated, reads the data from the buffers and echos it. On some systems, the amount of buffering is limited to a few thousand bytes. On Linux, it is nearly unlimited.
P1.javawhich is compiled by the command
javac P1.javaand run by the command
java P1Note also (see Q4 above) that it should be possible to run you program taking the “interactive” input from a file rather than the keyboard, with a command such as
java P1 < testfile