Using stdin with select() in C

18,371

Solution 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.

Solution 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.

Share:
18,371
Jake
Author by

Jake

# SOreadytohelp

Updated on June 09, 2022

Comments

  • Jake
    Jake almost 2 years

    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.

  • Jake
    Jake about 12 years
    If I have a running program, and I type in any text on console and press Enter, won't that be read by STDIN?
  • Ed Heal
    Ed Heal about 12 years
    @Jake - No. The console is just sending the input to thee program and you program is not reading it. The input is in a buffer until it is read by your code.