By default output to stdout
is line-buffered when connected to a terminal. That is, the buffer is flushed when it’s full or when you add a newline.
However, if stdout
is not connected to a terminal, like what happens when you redirect the output from your program to a file, then stdout
becomes fully buffered. That means the buffer will be flushed and actually written either when it’s full or when explicitly flushed (which happens when the program exits).
This means that the output of a separate process started from your code (like what happens when you call system
) will most likely be written first, since the buffer of that process will be flushed when that process ends, which is before your own process.
What happens when using redirection (or pipes for that matter):
- Your
printf
call writes to thestdout
buffer. - The
system
function starts a new process, which writes to its own buffer. - When the external process (started by your
system
call) exits, its buffer is flushed and written. Your own buffer in your own process, isn’t touched. - Your own process ends, and your
stdout
buffer is flushed and written.
To get the output in the “correct” (or at least expected) order, call fflush
before calling system
, to explicitly flush stdout
, or call setbuf
before any output to disable buffering completely.