Posted on 2009-05-06 10:03
Prayer 閱讀(903)
評論(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.
如果終端是標準輸出,它就是行緩存的,當遇到新行符,則被刷新一次。
如果標準輸出不是中斷,那它是全緩存的。如果緩沖區(qū)滿或者程序被終止,緩沖區(qū)被刷新。
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);"