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

后端 未结 3 1513
暗喜
暗喜 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:24

    Youre question sounds a little confused. select() is used to block until input is available. But you do the actual reading with normal file-reading functions (like read,fread,fgetc, etc.).

    Here's a quick example. It blocks until stdin has at least one character available for reading. But of course unless you change the terminal to some uncooked mode, it blocks until you press enter, when any characters typed are flushed into the file buffer (from some terminal buffer).

    #include 
    #include 
    
    int main(void) {
        fd_set s_rd, s_wr, s_ex;
        FD_ZERO(&s_rd);
        FD_ZERO(&s_wr);
        FD_ZERO(&s_ex);
        FD_SET(fileno(stdin), &s_rd);
        select(fileno(stdin)+1, &s_rd, &s_wr, &s_ex, NULL);
        return 0;
    }
    

提交回复
热议问题