Use select interface to write high precision delay.
select interface
int select(int maxfdp, fd_set *readset, fd_set *writeset, fd_set *exceptset,struct timeval *timeout);
principle
- Use the timeout parameter of select to implement a timer;
- Set the value of timeval, and set other parameters to NULL, select will exit when the internal time runs out.
Example
#include <stdio.h>
#include <sys/time.h>
int main()
{
struct timeval tv;
while(1)
{
tv.tv_sec = 1; // 定时1秒
tv.tv_usec = 0;
switch(select(0, NULL, NULL, NULL, &tv))
{
case -1: // 错误
printf("Error!\n");
break;
case 0: //超时
printf("timeout expires.\n");
break;
default:
printf("default\n");
break;
}
}
return 0;
}
void usleep(unsigned long usec)
{
struct timeval tv;
tv.tv_sec = usec / 1000000;
tv.tv_usec = usec % 1000000;
int err;
do {
err = select(0, NULL, NULL, NULL, &tv);
} while(err < 0 && errno == EINTR);
}
note
- The delay resolution supported by the kernel generally cannot reach the microsecond level;
- Due to the delay of kernel scheduling;
- The kernel resolution is generally a multiple of 10ms.