select函数的用法一
这个例子来自网上,调试修改后,粘贴如下:
#include <sys/time.h>#include <sys/types.h>#include <sys/stat.h>#include <assert.h>#include <unistd.h>#include <fcntl.h>int main(int argc, char **argv){int keyboard;int ret;char ch;fd_set readfd;struct timeval timeout;keyboard = open("/dev/tty", O_RDONLY|O_NONBLOCK);assert(keyboard > 0);while (1){timeout.tv_sec = 3;timeout.tv_usec = 0;FD_ZERO(&readfd);FD_SET(keyboard, &readfd); // 置位// 执行select函数时,首先记录置位的描述符,然后将所有位清零,从select函数返回前,有动作的描述符被再次置位ret = select(keyboard+1, &readfd, NULL, NULL, &timeout);if (FD_ISSET(keyboard, &readfd)) { // 如果置位,则表示有可读的信息read(keyboard, &ch, 1);if ('\n' == ch)continue;printf("key:%c\n", ch);if ('q' == ch)break;}else {printf("No input!\n");}}close(keyboard);}
?