我不明白缓冲区在做什么以及如何使用它。(另外,如果您可以解释缓冲区通常的作用)特别是,为什么在这个例子中我需要 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);
}
Run Code Online (Sandbox Code Playgroud)
在 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 操作数量就会少得多,这意味着应用程序速度更快。