gpt4 book ai didi

c - 误解 Unix 中的行缓冲区

转载 作者:太空狗 更新时间:2023-10-29 14:54:59 24 4
gpt4 key购买 nike

我正在阅读第 3 版 UNIX 环境中的高级编程,但误解了其中的一节(第 145 页,第 5.4 节缓冲,第 5 章)。

Line buffering comes with two caveats. First, the size of the buffer that the standard I/O library uses to collect each line is fixed, so I/O might take place if we fill this buffer before writing a newline. Second, whenever input is requested through the standard I/O library from either (a) an unbuffered stream or (b) a line-buffered stream (that requires data to be requested from the kernel), all line-buffered output streams are flushed. The reason for the qualifier on (b) is that the requested data may already be in the buffer, which doesn’t require data to be read from the kernel. Obviously, any input from an unbuffered stream, item (a), requires data to be obtained from the kernel.

我看不到粗线。我的英语不好。那么,你能为我澄清一下吗?也许以更简单的方式。谢谢。

最佳答案

所描述的阴谋背后的要点是确保在系统进入等待输入的模式之前出现提示。

如果输入流是无缓冲的,每次标准 I/O 库需要数据时,它都必须去内核获取一些信息。 (那是最后一句。)那是因为标准I/O库没有缓冲任何数据,所以当它需要更多数据时,它不得不从内核中读取。 (我认为即使是未缓冲的流也可能缓冲一个数据字符,因为它需要读取一个空格字符,例如,以检测它何时到达 %s 格式的末尾string;它必须放回 (ungetc()) 它读取的额外字符,以便下次需要一个字符时,它放回的那个字符。但它只需要一个缓冲的特性。)

如果一个输入流是行缓冲的,它的输入缓冲区中可能已经有一些数据,在这种情况下它可能不需要去内核获取更多数据。在那种情况下,它可能不会刷新任何东西。如果 scanf() 格式请求 "%s" 并且您键入了 hello world,就会发生这种情况;它会读取整行,但第一次扫描会在 hello 之后停止,而下一个 scanf() 将不需要为 world 进入内核 单词,因为它已经在缓冲区中。

但是,如果缓冲区中没有任何数据,它必须要求内核读取数据,并且它确保刷新任何行缓冲输出流,以便如果您编写:

printf("Enter name: ");
if (scanf("%63s", name) != 1)
…handle error or EOF…

然后出现提示(输入名称:)。但是,如果您之前键入了 hello world 并且之前只阅读了 hello,则提示不一定会出现,因为 world 已经在(行缓冲的)输入流中等待。

关于c - 误解 Unix 中的行缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23334147/

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