我不明白缓冲区是干什么的,怎么用的。 (另外,如果你能解释缓冲区通常做什么) 特别是,为什么在此示例中需要 fflush?
int main(int argc, char **argv)
{
int pid, status;
int newfd; /* new file descriptor */
if (argc != 2) {
fprintf(stderr, "usage: %s output_file\n", argv[0]);
exit(1);
}
if ((newfd = open(argv[1], O_CREAT|O_TRUNC|O_WRONLY, 0644)) < 0) {
perror(argv[1]); /* open failed */
exit(1);
}
printf("This goes to the standard output.\n");
printf("Now the standard output will go to \"%s\".\n", argv[1]);
fflush(stdout);
/* this new file will become the standard output */
/* standard output is file descriptor 1, so we use dup2 to */
/* to copy the new file descriptor onto file descriptor 1 */
/* dup2 will close the current standard output */
dup2(newfd, 1);
printf("This goes to the standard output too.\n");
exit(0);
}
最佳答案
在 UNIX 系统中,stdout 缓冲恰好可以提高 I/O 性能。 每次都做 I/O 会非常昂贵。
如果你真的不想缓冲,有一些选择:
禁用缓冲调用setvbuf http://www.cplusplus.com/reference/cstdio/setvbuf/
当你想刷新缓冲区时调用flush
输出到 stderr(默认无缓冲)
这里有更多详细信息:http://www.turnkeylinux.org/blog/unix-buffering
I/O 是一个昂贵的操作,所以为了减少 I/O 操作的次数,系统将信息存储在一个临时的内存位置,并延迟 I/O 操作到有大量数据的时刻.
这样您的 I/O 操作数量就会少得多,这意味着应用程序会更快。
关于有人可以解释一下 stdio 缓冲是如何工作的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29176636/