How to use select() to read input from keyboard in C

后端 未结 3 1516
暗喜
暗喜 2020-12-31 16:55

I am trying to use select() to read keyboard input and I got stuck in that I do not know how to read from keyboard and use a file descriptor to do so. I\'ve been told to use

3条回答
  •  长情又很酷
    2020-12-31 17:43

    As it was already said, by using select you can just monitor e.g. stdin to check if the input data is already available for reading or not. If it is available, you can then use e.g. fgets to safely read input data to some buffer, like shown below:

    #include 
    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
        fd_set rfds;
        struct timeval tv;
        int retval, len;
        char buff[255] = {0};
    
        /* Watch stdin (fd 0) to see when it has input. */
        FD_ZERO(&rfds);
        FD_SET(0, &rfds);
    
        /* Wait up to five seconds. */
        tv.tv_sec = 5;
        tv.tv_usec = 0;
    
        retval = select(1, &rfds, NULL, NULL, &tv);
    
        if (retval == -1){
            perror("select()");
            exit(EXIT_FAILURE);
        }
        else if (retval){
            /* FD_ISSET(0, &rfds) is true so input is available now. */
    
            /* Read data from stdin using fgets. */
            fgets(buff, sizeof(buff), stdin);
    
            /* Remove trailing newline character from the input buffer if needed. */
            len = strlen(buff) - 1;
            if (buff[len] == '\n')
                buff[len] = '\0';
    
            printf("'%s' was read from stdin.\n", buff);
        }
        else
            printf("No data within five seconds.\n");            
    
        exit(EXIT_SUCCESS);
    }
    

提交回复
热议问题