posts - 1256, comments - 190, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

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

Posted on 2009-05-06 10:03 Prayer 阅读(829) 评论(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.

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");
     }else if(pid > 0){

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

【推荐】超50万行VC++源码: 大型组态工控、电力仿真CAD与GIS源码库
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理