问题
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