Quote:
Originally Posted by gearoid_murphy
This will stop the program from freezing if there is not std input. My problem is that the program will not register input even if I pipe some into it. What really really bites is the fact that if I run an strace on the program, The program runs normally (it prints the piped input).
|
First, you don’t check to see the return value of read. Most likely, it’s
-1 and
errno is
EAGAIN.
Second, there is no guarantee that nonblocking input from a pipe will successfully read anything on the first try. Moreover, you are not guaranteed to read all the bytes at once.
Also, since you don’t check to see whether you have successfully read into the buffer, the contents of the buffer are 4096 bytes of stack space (p.s., not a good idea to use such a large buffer on the stack). Since this is uninitialized, your attempt to write it will result in the sequence of the first C-style string (e.g., all bytes from
buf[0] up until the first ascii nul character).
Additionally, your nonblocking trickery messes up on the majority of the cases you want to stop (when
stdin is a terminal, not a pipe). In this case, when you set
stdin to be nonblocking, you might also set
stdout and
stderr as nonblocking as well (since it’s all the same terminal). When you try to do buffered output (using
cout) to a non-blocking file, funny things can happen.
If you just want to check whether a file descriptor (in your case 0 for
stdin) is connected to a terminal, use the much more elegant (and portable) POSIX function
isatty().