Linux-IO多路复用select函数实践
1 #include <stdio.h> 2 #include <unistd.h> 3 #include <string.h> 4 #include <sys/time.h> 5 #include <sys/types.h> 6 #include <sys/stat.h> 7 #include <fcntl.h> 8 #include <sys/select.h> 9 10 int main(void) 11 { 12 int ret = -1; 13 int fd = -1; 14 char buf[100]; 15 fd_set myset; 16 struct timeval tm; 17 fd = open("/dev/input/mouse0",O_RDONLY); 18 if(fd < 0) 19 { 20 perror("open:"); 21 return -1; 22 } 23 FD_ZERO(&myset); 24 FD_SET(fd, &myset); 25 FD_SET(0, &myset); 26 tm.tv_sec = 10; 27 tm.tv_usec = 0; 28 ret = select(fd + 1, &myset, NULL, NULL, &tm); 29 if(ret < 0) 30 { 31 perror("select:"); 32 return -1; 33 } 34 else if(ret == 0) 35 { 36 printf("超时了\n"); 37 } 38 else 39 { 40 if(FD_ISSET(fd, &myset)) 41 { 42 //处理鼠标 43 memset(buf, 0, sizeof(buf)); 44 read(fd, buf, 2); 45 printf("读出的鼠标:[%s]\n",buf); 46 } 47 if(FD_ISSET(0, &myset)) 48 { 49 //处理键盘 50 memset(buf, 0, sizeof(buf)); 51 read(0, buf, 2); 52 printf("读出的键盘:[%s]\n",buf); 53 } 54 } 55 return 0; 56 }