gpt4 book ai didi

c - 关于 UNIX 系统中的无缓冲 I/O

转载 作者:太空狗 更新时间:2023-10-29 16:07:32 25 4
gpt4 key购买 nike

我最近一直在阅读 APUE,这时出现了一个基本问题。我的代码如下所示


#include <apue.h>
#define BUFFSIZE 4096
int main()
{
int n;
char buf[BUFFSIZE];
while((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
{
printf("n is %d\n", n); //this line is added by me for testing
if(write(STDOUT_FILENO, buf, n) != n)
err_sys("write error"); //functions defined by the book to print error message
}

if(n < 0)
err_sys("read error");
exit(0);
}

编译后,当我运行程序时如下图所示

> $ ./mycat
123456[enter]
n is 7
123456
1234[enter]
n is 5
1234

看起来它按照我的代码结构工作。而且我不太明白'enter'的功能。每次我按下“enter”时,读取函数都会终止并将包括“enter”产生的“\n”在内的字符传递给写入函数。所以它进入循环并首先打印读取的字符数。


但是,下面的测试似乎违背了上面的代码结构。

> $ ./mycat > data
123456[enter]
1234[enter]
^D
> $ cat data
123456
1234
n is 7
n is 5

程序好像是先把所有的字符写入文件,然后打印'n'的值,但是按照我的理解,应该先打印如下

n is 7
123456
n is 5
1234

想了又想,就是想不通。你能帮帮我吗?

最佳答案

write() 缓冲。 printf()发送到 stdout 缓冲的,但在某种程度上取决于输出的位置。

如果stdout的输出进入控制台,它是行缓冲的,如果不是,它是完全缓冲的,在你的第二个例子中导致在程序结束时被刷新,而调用 write() 的输出马上出去。

来自 man stdio :

[...] the standard input and output streams are fully buffered if and only if the streams do not refer to an interactive device.

Output streams that refer to terminal devices are always line buffered by default;

关于c - 关于 UNIX 系统中的无缓冲 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22425725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com