gpt4 book ai didi

C - 当标准输入的缓冲区中已有数据时,在标准输入上选择()

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:44 25 4
gpt4 key购买 nike

The select function blocks the calling process until there is activity on any of the specified sets of file descriptors [...] A file descriptor is considered ready for reading if a read call will not block. (See: https://www.gnu.org/software/libc/manual/html_node/Waiting-for-I_002fO.html)

所以我预计,如果您在第一次迭代中输入大于 4 个字符的字符串,则以下程序中的 select 会在第二次迭代中立即返回。然而事实并非如此。在第一次输出后按下任何其他键后,它会继续处理所有剩余的输入。为什么?

示例输出:

./selectTest
12345678900
Keyboard input received: 1234
A
Keyboard input received: 5678
Keyboard input received: 900

Keyboard input received: A

代码

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int main(void)
{
fd_set rfds;
char buf[100];

while(1)
{
FD_ZERO(&rfds);
FD_SET(fileno(stdin), &rfds);

if(-1 == select(FD_SETSIZE, &rfds, NULL, NULL, NULL))
{
perror("select() failed\n");
}

if(FD_ISSET(fileno(stdin), &rfds))
{
printf("Keyboard input received: ");
fgets(buf, 5, stdin);
printf("%s\n", buf);
}
}
return 0;
}

(我知道,我不应该再使用 select(),但我正在为考试而学习,我们必须......)

最佳答案

从根本上说,问题在于您将缓冲的 stdio 流与低级 I/O 混合在一起。 select 阻塞的原因是因为先前键入的数据已被读取并缓冲在 stdin 的流数据缓冲区中。尝试通过调用 setbuf(stdin, NULL)stdin 设置为无缓冲模式。

关于C - 当标准输入的缓冲区中已有数据时,在标准输入上选择(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34067884/

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