Thread: Problem Reading from console using select

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    1

    Problem Reading from console using select

    Code:
    /*
    ** select.c -- a select() demo
    */
    
    #include <stdio.h>
    #include <sys/time.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <termios.h>
    #include <stropts.h>
    
    #define STDIN 0  // file descriptor for standard input
    
    int main(void)
    {
        struct timeval tv;
        fd_set readfds;
        fd_set master;
    
        tv.tv_sec = 5;
        tv.tv_usec = 500000;
        //struct termios term;
        
        FD_ZERO(&master);
        FD_ZERO(&readfds);
        FD_SET(STDIN_FILENO, &master);
        
        // don't care about writefds and exceptfds:
        while(1){
        
        readfds=master;
        /*tcgetattr(STDIN, &term);
        term.c_lflag &= ~ICANON;
        tcsetattr(STDIN, TCSANOW, &term);
        setbuf(stdin, NULL);*/
        select(STDIN+1, &readfds, NULL, NULL, NULL);
       
    
        if (FD_ISSET(STDIN_FILENO, &readfds)){
            printf("A key was pressed!\n");
            //FD_CLR();
            fflush(stdout);
        }
        else
            printf("Timed out.\n");
        }
        return 0;
    }
    why prog goes in infinite loop after 1st enter? i want to read single lines just like gets()

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    select doesn't READ stdin, it just tells you that there is something there.

    You need to call some actual read function to consume data.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Socket Select problem
    By saipkjai in forum Networking/Device Communication
    Replies: 4
    Last Post: 02-08-2008, 10:57 AM
  2. reading from pts's by select
    By fnoyan in forum Linux Programming
    Replies: 0
    Last Post: 12-16-2005, 04:02 AM
  3. select() problem
    By nkhambal in forum Networking/Device Communication
    Replies: 3
    Last Post: 07-12-2005, 11:34 AM
  4. problem with select
    By IceBall in forum Networking/Device Communication
    Replies: 2
    Last Post: 03-25-2004, 02:23 PM
  5. another select problem...
    By brita in forum Windows Programming
    Replies: 0
    Last Post: 04-07-2003, 01:54 AM