代码演示:
select每次重新监听时需要重新设置“集合”和“超时时间”,因为每次select监听结束时会清空“集合”和“超时时间”。
int main(int argc, char *argv[])
{
int ret = 0;
int mousefd = 0;
fd_set readfds;
char buf[100] = {0};
char buf1;
struct timeval timeover;
mousefd = open("/dev/input/mouse0", O_RDONLY);
if (mousefd == -1) print_err("open /dev/input/mouse0 fail", __LINE__, errno);
while(1)
{
timeover.tv_sec = 3;
timeover.tv_usec = 30;
FD_ZERO(&readfds);//Empty file descriptor set
FD_SET(0, &readfds);//Add the file descriptor 0 to the set
FD_SET(mousefd, &readfds);//Add the file descriptor mousefd to the set
//int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
label: ret = select(mousefd+1, &readfds, NULL, NULL, &timeover);
if (ret == -1 && ret == EINTR) goto label;
else if (ret == -1) print_err("select ", __LINE__, errno);
/* If there is movement in the file descriptor set */
else if (ret > 0)
{
/* Determine which file descriptor it is */
/* TURE:1, false:0 */
if (FD_ISSET(0, &readfds))
{
bzero(buf, sizeof(buf));
ret = read(0, buf, sizeof(buf));
if (ret > 0) printf("%s\n", buf);
}
if (FD_ISSET(mousefd, &readfds))
{
bzero(&buf1, sizeof(buf1));
ret = read(mousefd, &buf1, sizeof(buf1));
if (ret > 0) printf("%d\n", buf1);
}
}
else if (ret == 0)
{
printf("time out\n");
}
}
return 0;
}