结论
使用write函数直接输出到输出设备上,是不带缓冲;但是标准IO库是带有缓冲的,printf遇到 的时候才会冲刷缓冲区,输出到输出设备上。
测试程序
如下:
1 #include "apue.h" 2 3 int globvar = 6; 4 char buf[] = "a write to stdout "; 5 6 int main() 7 { 8 int var; 9 pid_t pid; 10 11 var = 88; 12 if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != 13 sizeof(buf) -1) 14 { 15 err_sys("write error"); 16 } 17 printf("before fork "); 18 sleep(3); 19 if ((pid = fork()) < 0) 20 err_sys("fork error"); 21 else if (pid == 0) { 22 globvar++; 23 var++; 24 } else { 25 sleep(2); 26 } 27 28 printf("pid = %ld, glob = %d, var = %d ", 29 (long)getpid(), globvar, var); 30 exit(0); 31 32 }
输出结果
如下
a write to stdout
// sleep 3s
before fork pid = 27219, glob = 7, var = 89
// sleep 2s
before fork pid = 26934, glob = 6, var = 88