Prayer

在一般中寻求卓越
posts - 1256, comments - 190, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

UNIX 标准输入 全缓存和行缓存 的区别

Posted on 2009-05-06 10:03 Prayer 阅读(887) 评论(0)  编辑 收藏 引用 所属分类: LINUX/UNIX/AIX

This case may relates to stdio buffering.
If stdout is a terminal, it is line buffered. The buffer is flushed when a new line is hit.
Otherwise, stdout is fully buffered. The buffer is flushed if the buffer is full or the program terminates.flush means clear the stdout.
如果终端是标准输出,它就是行缓存的,当遇到新行符,则被刷新一次。
如果标准输出不是中断,那它是全缓存的。如果缓冲区满或者程序被终止,缓冲区被刷新。


So
1) we run bpeek directly, the printf() function is line buffered, when "\n" is hit, the buffer is flushed immediately and "<< output from stdout >>" is printed.
2) we run bpeek|tail, the printf() functions became fully buffered, when "\n" is hit, the buffer is NOT flushed. The buffer resides in the process's memory. When the process execute fork(), the son gets a copy from the father's memory, that means both father and son process have the unflushed buffer. When the son process exits, the message is printed. When the father exits, the message is printed again.

We can write a simple program to simulate this:
----------------------------
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
        pid_t pid;

        printf("<< %s >>\n", "output of stdout");
        pid = fork();

     if(pid < 0){
          printf("fork error\n");
          exit(-1);
     }else if(pid > 0){
          wait(NULL);
          return;
     }
     exit(0);
}


"To avoid this, we my force printf() to line buffered:
setvbuf(stdout, buf, _IOLBF, BUFSIZ);"


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理