#include <sys/types.h>
#include "ourhdr.h"
int main()
{
char buf[]="a write to stdout/n";
size_t size=sizeof(buf);
write(STDOUT_FILENO, buf, size);
printf("hello/n"); /* we don't flush stdout */
if(fork() == 0)
sleep(2);
printf("world/n");
exit(0);
}
# a.out
a write to stdout
hello
world
world
# a.out > file
# cat file
a write to stdout
hello
world
hello
world
1.标准IO库是带缓存的,如果标准输出连到终端设备,则它是行缓存,否则是全缓存。
2.当以交互方式运行该程序时,因为标准输出是行缓存,所以缓存被新行符"/n"刷新,printf("hello/n");只输出一次。
若改为printf("hello ");则会输出2次。
3.标准输出重定向至文件时,因为标准输出是全缓存,当调用fork时"hello/n"仍在缓存中,在父进程数据空间复制到子进程中时,该缓存数据也被复制到子进程中。于是第二个printf函数执行输出数据"world"前会将数据添加到现在的缓存中,直到执行exit或全缓存空间满才会一次性输出全缓存的内容"hello/n"+"world/n"。
4.write()是不带缓存IO,故不似标准IO要考虑缓存问题。