系统函数read和write是不带缓冲的,而c的标准io函数是带缓冲的,
(1)当io函数与stderr相连时 是不带缓冲的(为了错误能够快速输出)
(2)当与stdin和stdout相连是行缓冲的(即遇到换行符就输出)
(3)与其他的相连都是全缓冲的(缓冲区满了才输出)
可以用一个小例子试一下,参考 《unix环境高级编程》 8.1
# include <stdio.h>
# include <apue.h>
int globvar = 6;
char buf[] = "a write to stdtou\n";
int main(){
int var;
pid_t pid;
var = 88;
char *ma_buf = (char *) malloc(100);
strcpy(ma_buf,"hahahaha");
if(write(STDOUT_FILENO,buf,sizeof(buf)-1) != sizeof(buf)-1)
err_sys("write error");
printf("before fork _huanhang\n");
printf("before fork :");
if( (pid = fork()) < 0 ){
err_sys("fork error");
} else if(pid == 0){
var = 88;
globvar ++;
printf("child: ma_buf = %s\n",ma_buf);
} else {
sleep(2);
printf("parent: ma_buf = %s\n",ma_buf);
}
printf("pid = %ld, globvar = %d, var = %d\n",(long)getpid(),globvar,var);
}
结果:
ncx@ncx-tp:~/code$ gcc 8_1.c
<strong>ncx@ncx-tp:~/code$ ./a.out // 1</strong>
a write to stdtou
before fork _huanhang<span style="white-space:pre"> </span>
before fork :child: ma_buf = hahahaha
pid = 20593, globvar = 7, var = 88
before fork :parent: ma_buf = hahahaha
pid = 20592, globvar = 6, var = 88
<strong>ncx@ncx-tp:~/code$ ./a.out > tmp // 2
ncx@ncx-tp:~/code$ cat tmp</strong>
a write to stdtou
before fork _huanhang
before fork :child: ma_buf = hahahaha
pid = 20595, globvar = 7, var = 88
before fork _huanhang
before fork :parent: ma_buf = hahahaha
pid = 20594, globvar = 6, var = 88
write 不带缓冲所以1 2都指数出一次
printf “before fork _huanhang”在1中与终端stdout相连是行缓冲的,所以在1中只输出一次
而在2中是与tmp相连的是全缓冲的,fork之后会把缓冲区一起复制,所以before fork _huanhang会输出两次
printf “before fork”因为没有遇到换行符 所以在1,2中都输出两次