line buffered:遇到换行或者缓冲区满再做flush
fully buffered:缓冲区满做flush
标准输出和终端设备相连时(例如默认情况下stdout 为显示器,或者嵌入式设备中的stdout为
串口终端)它是line buffered,否则是(例如./a.out > temp.out 采用">"将输出重定位到文件)fully buffered。
_____________________________________________________________________________________
以APUE 例8.1说明
程序如下:
#include "apue.h" int glob = 6; /* external variable in initialized data */ char buf[] = "a write to stdout\n"; int main(void) { int var; /* automatic variable on the stack */ pid_t pid; var = 88; if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1) err_sys("write error"); printf("before fork\n"); /* we don't flush stdout */ if ((pid = fork()) < 0) { err_sys("fork error"); } else if (pid == 0) { /* child */ glob++; /* modify variables */ var++; } else { sleep(2); /* parent */ } printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var); exit(0); }的输出结果为
$ ./a.out a write to stdout before fork pid = 430, glob = 7, var = 89 child's variables were changed pid = 429, glob = 6, var = 88 parent's copy was not changed $ ./a.out > temp.out $ cat temp.out a write to stdout before fork pid = 432, glob = 7, var = 89 before fork pid = 431, glob = 6, var = 88
所以可以发现采用重定位输出后,printf缓冲区的内容也一起被复制到子进程,
直到在exit之前才做flush,将所有缓冲区中的内容一起输出到文件