全缓冲和行缓冲的区别

来源:互联网 发布:metinfo模板 源码 编辑:程序博客网 时间:2024/04/30 13:14

 转载地址:http://blog.csdn.net/lxmky/article/details/5457324

在*nix系统中,缓冲方式存在三种,分别是:

1,全缓冲

2,行缓冲

3,无缓冲

在学习APUE这本书时,程序8-1中,就很好的体现了全缓冲和行缓冲的区别,代码如下:

[cpp] view plaincopy
  1. #include<stdio.h>  
  2. #include<unistd.h>  
  3. int glob=6;  
  4. char buf[]="a write ro stdout/n";  
  5. int main()  
  6. {  
  7.         int var;  
  8.         pid_t pid;  
  9.         printf("a write to stdout/n");  
  10.         fflush(NULL);  
  11.         if((pid=fork())<0)  
  12.         {  
  13.                 printf("fork error");  
  14.         }  
  15.         else  
  16.         {  
  17.                 if(pid==0)  
  18.                 {  
  19.                         glob++;  
  20.                         var++;  
  21.                 }  
  22.                 else  
  23.                 {  
  24.                         sleep(2);  
  25.                 }  
  26.         }  
  27.         printf("pid=%d,glob=%d,var=%d/n",getpid(),glob,var);  
  28.         exit(0);  
  29. }  
 

编译成功后,我这里生成的二进制文件默认为a.out

运行:./a.out

可以看到结果如下:

[c-sharp] view plaincopy
  1. a write to stdout  
  2. pid=6587,glob=7,var=134514042  
  3. pid=6586,glob=6,var=134514041  
 

运行./a.out > temp.out

结果如下:

[c-sharp] view plaincopy
  1. a write to stdout  
  2. pid=6591,glob=7,var=134514042  
  3. a write to stdout  
  4. pid=6590,glob=6,var=134514041  

分析原因:

在./a.out输出中,标注输出是STDOUT_FILENO,是交互式的终端,所以系统采用的缓冲方式行缓冲,很快被新的一行冲掉,重定向后,标准输出是全缓冲。当调用fork时 a write to stdout这行仍然保存在缓冲中,并随着数据段复制到子进程缓冲中,这样,这一行就分别进入父子进程的输出缓冲中,


0 0
原创粉丝点击