Using stdin with select() in C

老子叫甜甜 提交于 2019-11-29 15:15:04

问题


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.


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




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



来源:https://stackoverflow.com/questions/10219340/using-stdin-with-select-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!