2
votes

I wrote a program capture which output stdout message as well as stderr message (i.e, printf(), fprintf(stderr,..))

and I want the print information to be displayed on terminal as well as saved into log file.

  ./capture 2>&1|tee log

but I see that the stdout and stderr messages seem not to be in order in the log file.

does output redirection write stdout and stderr info in order? if not, what can I do to make them in order?

1

1 Answers

0
votes

Output redirection as it is keeps the order of your write() calls. Redirection only changes the file descriptor structure in the kernel held for the process, copying the value from under fd1 into fd2.

Your problem is that *printf() buffers the output batching some write() calls. Normally no buffering for stderr and line-buffering for stdout is used. But as you redirect it into a pipe, it switches to block buffering for stdout, delaying the output (See man stdout). Turn the buffering mode to line manually with setlinebuf(stdout); at the beginning, or use fflush(stdout); after every *printf(). Or just use raw write() calls. You can read about this in man setlinebuf.

In bash actually you can do that redirection with |& as well. Check out man bash about Pipelines.