There are several kinds of buffering going on. The input to the program is buffered by the pseudoterminal device's Line-buffering discipline. On the output side, there is a file-system cache (a buffer in the OS for the whole file), and extra buffering in the C program when printing to a FILE *
type. But read
and write
bypass the FILE *
buffering and move data more or less directly to/from the file-system cache.
So it appears that your stdout
buffer is being flushed automatically when all output is going to the terminal, but not when redirected to a file. So I'd recommend adding a call to
fflush(stdout);
after the printf
call. This should explicitly flush the buffer (and enforce the ordering of the output that you want).
The important thing to be aware of is when you're using FILE *
s which are a C-level structure manipulated by library functions (like fopen
), and when you're using the raw file descriptor (which is just an integer, but refers to the underlying operating-system file). The FILE
datatype is a wrapper around this lower level Unix implementation detail. The FILE
functions implement an additional layer of buffering so the lower level can operate on larger blocks, and you can efficiently perform byte-at-a-type processing without doing lots and lots I/O handshakes.