So true. After re-examining the codes, I found that those output
which appeared before "program starts." were generated by
"fprintf(stderr,..)" in functions called by main().
What gives?
stdout and stderr are different streams. They are not required to
synchronize their output (which may be directed to different
destinations; the Standard certainly allows that). They are not
required to have the same buffering mode. In particular:
When opened, the standard error stream is not fully buffered;
the standard input and output streams are fully buffered if
and only if the stream can be determined not to refer to an
interactive device. (C90 7.9.3)
C defines three buffering modes for streams: unbuffered, line
buffered, and fully buffered. The last cannot be used for stderr,
which leaves the implementation two options. It can (and must) only
be used for stdin and stdout if the implementation knows that they're
not connected to an interactive device; that also leaves two options,
if they *are* connected to an interactive device.
Buffering modes can be changed with the setbuf and setvbuf functions.
OT: Typically, for Unix-derived implementations, stderr is unbuffered
and stdout is line-buffered, when they're connected to a tty. When
stdout is not connected to a tty, it must be fully buffered. Thus,
for example, on one implementation:
$ cat testc.c
#include <stdio.h>
int main(void)
{
fputs("from stdout\n", stdout);
fputs("from stderr\n", stderr);
return 0;
}
$ ./testc
from stdout
from stderr
$ ./testc | cat
from stderr
from stdout
In the second case, piping stdout means it must be fully-buffered, so
its output appears only when the buffer is full or the stream is
flushed, as it is when it's implicitly closed at program termination.
Stream buffering is not the whole story, however. What happens when
the C library passes outbound data to the environment is an
implementation and environmental issue.
If you're concerned about only this one line appearing first, you
could try fflush(stdout); it's not guaranteed to have the effect you
want, but it's a start.
If in general you want output to stdout and stderr to happen in the
order in which your program performs it, you could try setting them
both to be unbuffered. Again, there are no guarantees.
--
Michael Wojcik (e-mail address removed)
However, we maintain that our mission is more than creating high-tech
amusement--rather, we must endeavor to provide high-tech, high-touch
entertainment with an emphasis on enkindling human warmth.
-- "The Ultimate in Entertainment", from the president of video game
producer Namco