You have your output line in the stdout
buffer, because you have not ended it in a '\n'
. If you end your output line with it, you'll se the line printed before the call to system.
The reason is that stdio
uses line buffer if the output device is a terminal. It buffers all the characters until the buffer is full (this is difficult to see, as a full buffer can be as big as 16-32kb, it varies from system to system) or a new line is output. Then the buffer is flushed. But you didn't use a '\n'
, so the buffer is waiting until the program ends after the call to system(3)
.
You have several ways to solve this:
- You can force the buffer flush by calling
fflush(stdout);
. This will make stdio
to write the buffer as it is, and you will see your line followed (without a new line) by the output of your system()
command.
- You can tell
stdio
not to use a buffer on stdout. This is done with setbuf(stdout, NULL);
. In this way, every printf()
you make will be written as the strings are being formatted, as there's no buffer to hold them off.
- You can end your output in a
'\n'
. You'll see how different the output is by just putting a new line before the call to system()
.
In case your output is not to a tty device, but to a file, then the situation is worse, as then the buffer flush is done only when the buffer fills completely (not on line endings) and you'll see the full output of your system()
call before all the output of your program (assuming you print several lines before calling printf()
and both, the called program and the output of this one are redirected to a file)