[英]Can someone please explain how stdio buffering works?
我不明白緩沖區在做什么以及它是如何使用的。 (另外,如果你能解釋緩沖區通常做什么)特別是,為什么在這個例子中我需要 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 系統中,標准輸出緩沖恰好可以提高 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 操作數量要少得多,這意味着應用程序速度更快。
danielfraca 回答了大部分問題,但還有另一部分:流上的默認緩沖是什么?
當且僅當它引用終端時,默認情況下輸出流是行緩沖的。 否則它是全緩沖的。 另請注意,如果寫入的字節數超過BUFSIZ
(通常為 512 和 8192 之間的 2 的冪),則兩種緩沖都將自動刷新。
所以這個程序:
#include <stdio.h>
#include <unistd.h>
int main()
{
puts("Hello");
fork();
puts("World");
}
產生這個輸出:
% ./fork
Hello
World
World
% ./fork | cat
Hello
World
Hello
World
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.