How to use select to read input from stdin?

别说谁变了你拦得住时间么 提交于 2019-12-25 07:04:59

问题


I am trying to read from stdin using select, after that I am sending the data through a socket to a server.

The following snippet is supposed to follow the above logic; but it doesn't read anything from stdin.

Moreover it prints Enter command: after the first time the user inputs a string. The line printf("%d %s\n",__LINE__ ,buf); doesn't print anything as either.

fd_set rfds;
struct timeval tv;
int retval; 
char buf[BUFLEN];
while(1) {
    FD_ZERO(&rfds);
    FD_SET(STDIN_FILENO, &rfds);
    tv.tv_sec = 5;
    tv.tv_usec = 0;
    retval = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv);
    if (FD_ISSET(STDIN_FILENO, &rfds)) {
        if (fgets(buf,BUFLEN, stdin)) {
              printf("%d %s\n",__LINE__ ,buf);
          if (strncmp(buf, "exit", 4) == 0)
                exit(0);
         }
         printf("\nEnter command: ");
    }
}

why do I get only Enter command: printed endlessly ?

Edit: the problem was with the embedded device I was using and somehow compile it with -fpic fixed the problem.


回答1:


Try

FD_ZERO(&rfds);
FD_SET(STDIN_FILENO, &rfds);

Inside the while loop



来源:https://stackoverflow.com/questions/16510831/how-to-use-select-to-read-input-from-stdin

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