写()到标准输出和printf输出不交叉存取? [英] write() to stdout and printf output not interleaved?
问题描述
#include <stdio.h>
#define MAXLEN 256
int main() {
int n;
char buf[MAXLEN];
while((n = read(0,buf,sizeof(buf))) != 0){
printf("n: %d:",n);
write(1,buf,n);
}
return 1;
}
的
程序的输出是
The output of the program is
read
read
write
write
n: 5:n: 6:
的printf的输出来pressing后ctrl + D的标准输入,而不是非常久远的后续读取。 Ÿ会出现这种情况?
The output of printf comes after pressing Ctrl+D at the standard input and not alongwith the subsequent reads. Y does this happen?
推荐答案
printf的缓冲。
Printf is buffered.
您可以使用fflush调用强制printf的'刷新'它的缓存:
You can force printf to 'flush' its buffer using the fflush call:
#include <stdio.h>
#define MAXLEN 256
int main() {
int n;
char buf[MAXLEN];
while((n = read(0,buf,sizeof(buf))) != 0){
printf("n: %d:",n);
fflush(stdout); /* force it to go out */
write(1,buf,n);
}
return 1;
}
在一般情况下,的printf()
被缓冲是一件好事。无缓冲输出,特别是那些需要屏幕更新和可见这样的游戏机,是缓慢的。慢,以至于被printf'ing大量的应用程序可以通过它直接趋缓(尤其是Windows平台,Linux和Unix系统通常影响更小)。
In general, printf()
being buffered is a good thing. Unbuffered output, particularly to visible consoles that require screen updates and such, is slow. Slow enough that an application that is printf'ing a lot can be directly slowed down by it (especially on the Windows platform; Linux and unixes are typically impacted less).
然而,的printf()
被缓冲确实咬你,如果你还 fprintf中(标准错误,)
- 标准错误
是故意无缓冲。因此,你可能会与某些的printf()
缺失让你的消息;如果你写的另一个文件
处理,它也与终端有关,可能是无缓冲,确保你第一次明确地 fflush(标准输出)
。
However, printf()
being buffered does bite you if you also fprintf(stderr,)
- stderr
is deliberately unbuffered. As a consequence, you may get your messages with some printf()
missing; if you write to another FILE
handle that is also associated with the terminal, and might be unbuffered, make sure you first explicitly fflush(stdout)
.
这篇关于写()到标准输出和printf输出不交叉存取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!