Using stdin with select () in C

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 am facing is that as soon as the input is found in STDIN, the message "User input - stdin" continues to print ... why it does not print only once and the next, and the loop checks which of the descriptors has an input

Thanks.

+3
source share
2 answers

The function selectonly reports when there is an input available. If you do not actually consume it, the choice will continue to fall directly.

+8
source

Because you are not reading STDIN, so next time there is still something to read around the loop.

, STDIN.

+3

Source: https://habr.com/ru/post/1526912/


All Articles