Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 372
Jake Avatar asked Apr 18 '12 23:04

Jake


1 Answers

The select function only tells you when there is input available. If you don't actually consume it, select will continue falling straight through.

like image 153
Marcelo Cantos Avatar answered Oct 03 '22 15:10

Marcelo Cantos