select实现精确定时器
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); struct timeval { long tv_sec; long tv_usec; } /* seconds and microseconds */
秒级定时器
void sec_sleep(unsigned sec) { int err; struct timeval tv; tv.tv_sec = sec; tv.tv_usec = 0; do { err = select(0, NULL, NULL, NULL, &tv); } while (err < 0 && errno == EINTR); }
毫秒级定时器
void msec_sleep(unsigned long msec) { int err; struct timeval tv; tv.tv_sec = msec / 1000; tv.tv_usec = (msec % 1000) * 1000; do { err = select(0, NULL, NULL, NULL, &tv); } while (err < 0 && errno == EINTR); }
微秒级定时器
void usec_sleep(unsigned long usec) { int err; struct timeval tv; tv.tv_sec = usec / 1000000; tv.tv_usec = usec % 1000000; do { err = select(0, NULL, NULL, NULL, &tv); } while (err < 0 && errno == ENTR); }
时间: 2024-10-11 22:05:24