问题
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 ?
Thanks.
回答1:
The select
function only tells you when there is input available. If you don't actually consume it, select will continue falling straight through.
回答2:
Because you are not reading STDIN, so next time around the loop there is still something to read.
You need to read STDIN to prevent this.
来源:https://stackoverflow.com/questions/10219340/using-stdin-with-select-in-c