1.poll超时检测
#include <myhead.h> int main(int argc, char const *argv[]) { struct pollfd pfd = { .fd = 0, .events = POLLIN, }; while (1) { int res = poll(&pfd, 1, 5000); if (res == -1) { perror("poll error"); return -1; } else if (res == 0) { printf("time out"); return -1; } else if (pfd.revents == POLLIN) { int num = 0; scanf("%d", &num); printf("键盘输入:%d\n", num); } } return 0; }
2.select中的超时检测
#include <myhead.h> int main(int argc, char const *argv[]) { fd_set readfds; FD_ZERO(&readfds); FD_SET(0, &readfds); while (1) { struct timeval tv = {5, 0}; int res = select(1, &readfds, NULL, NULL, &tv); if (res == -1) { perror("select error"); return -1; } else if (res == 0) { printf("time out\n"); return -1; } if (FD_ISSET(0, &readfds)) { int num = 0; scanf("%d", &num); printf("键盘输入:%d\n", num); } } return 0; }
3.通过信号完成时间设置
#include <myhead.h> void handler(int signo) { if (signo == SIGALRM) { printf("时间到了!\n"); } } int main(int argc, const char *argv[]) { if (signal(SIGALRM, handler) == SIG_ERR) { perror("signal error"); return -1; } alarm(5); return 0; }
4. IO多路复用的原理
可实现的函数有三种:①select ②poll ③epoll