Linux 在 C 中将 stdin 与 select() 结合使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10219340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using stdin with select() in C
提问by Jake
I have the following program:
我有以下程序:
#include <stdio.h>
#define STDIN 0
int main()
{
fd_set fds;
int maxfd;
// sd is a UDP socket
maxfd = (sd > STDIN)?sd:STDIN;
while(1){
FD_ZERO(&fds);
FD_SET(sd, &fds);
FD_SET(STDIN, &fds);
select(maxfd+1, &fds, NULL, NULL, NULL);
if (FD_ISSET(STDIN, &fds)){
printf("\nUser input - stdin");
}
if (FD_ISSET(sd, &fds)){
// socket code
}
}
}
The problem I face is that once input is detected on STDIN, the message "User input - stdin" keeps on printing...why doesn't it print just once and on next while loop check which of the descriptors has input ?
我面临的问题是,一旦在 STDIN 上检测到输入,消息“用户输入 - 标准输入”就会继续打印……为什么它不只打印一次,然后在下一个 while 循环检查哪个描述符有输入?
Thanks.
谢谢。
采纳答案by Marcelo Cantos
The select
function only tells you when there is input available. If you don't actually consume it, select will continue falling straight through.
该select
功能仅在有可用输入时告诉您。如果您实际上不消耗它,则 select 将继续直接下降。
回答by Ed Heal
Because you are not reading STDIN, so next time around the loop there is still something to read.
因为您没有阅读 STDIN,所以下次循环时仍然有一些东西要阅读。
You need to read STDIN to prevent this.
您需要阅读 STDIN 以防止这种情况发生。