How to use select to read input from stdin?

2019-09-01 08:05发布

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条回答
神经病院院长
2楼-- · 2019-09-01 08:50

Try

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

Inside the while loop

查看更多
登录 后发表回答