先看下面一個例子a.c :
代碼如下:
int main(int argc, char *argv[])
{
fprintf(stdout, "normal\n");
fprintf(stderr, "bad\n");
return 0;
}
$ ./a
normal
bad
$ ./a > tmp 2>&1
$ cat tmp
bad
tmp
我們看到, 重定向到一個文件後, bad 到了 normal 的前面.
原因如下:代碼如下:
"The stream stderr is unbuffered. The stream stdout is line-buffered when it points to a
terminal. Partial lines will not appear until fflush(3) or exit(3) is called, or a newline
is printed. This can produce unexpected results, especially with debugging output. The
buffering mode of the standard streams (or any other stream) can be changed using the
setbuf(3) or setvbuf(3) call. "
因此, 可以使用如下的代碼:
代碼如下:
int main(int argc, char *argv[])
{
fprintf(stdout, " normal\n");
fflush(stdout);
fprintf(stderr, " bad\n");
return 0;
}
這樣重定向到一個文件後就正常了. 但是這種方法只適用於少量的輸出, 全局的設置方法還需要用 setbuf() 或 setvbuf(), 或者采用下面的系統調用:
代碼如下:
int main(int argc, char *argv[])
{
write(1, "normal\n", strlen("normal\n"));
write(2, "bad\n", strlen("bad\n"));
return 0;
}
但是盡量不要同時使用 文件流 和 文件描述符,
代碼如下:
"Note that mixing use of FILEs and raw file descriptors can produce unexpected results and
should generally be avoided. A general rule is that file
descriptors are handled in the kernel, while stdio is just a library. This means for exam-
ple, that after an exec(), the child inherits all open file descriptors, but all old
streams have become inaccessible."