向rtc设备设置一个周期时间,在循环中每次时间到达时调用。需要管理员权限运行。
#include <stdio.h>
#include <linux/rtc.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
unsigned long i = 0;
unsigned long data = 0;
//int retval = 0;
int fd = open("/dev/rtc", O_RDONLY); //打开RTC
if (fd < 0)
{
perror("open");
exit(errno);
}
//set the freq
if (ioctl(fd, RTC_IRQP_SET, 1) < 0) //RTC_IRQP_SET 设定当前周期性中断的频率
{
perror("ioctl(RTC_IRQP_SET)");
close(fd);
exit(errno);
}
//enable periodic interrupts
if (ioctl(fd, RTC_PIE_ON, 0) < 0) //打开周期性中断
{
perror("ioctl(RTC_PIE_ON)");
close(fd);
exit(errno);
}
struct timeval tvstart, tvend;
for (i=0; i<50; i++)
{
gettimeofday(&tvstart, 0);
int res = read(fd, &data, sizeof(unsigned long)); //读取rtc设备
if (res < 0)
{
perror("read");
close(fd);
exit(errno);
}
gettimeofday(&tvend, 0);
printf("timer %lld\n", (tvend.tv_sec - tvstart.tv_sec)*1000000LL+(tvend.tv_usec - tvstart.tv_usec));
}
//disable periodic interrupts
ioctl(fd, RTC_PIE_OFF, 0); //关闭周期性中断
close(fd);
return 0;
}
int FREQ = 2048;
ioctl(g_fd, RTC_IRQP_SET, FREQ) ;
频率是2048,网上说频率可用范围是2~8192,一定要是2的n次方, 但是在试验时,1,3,5等值也可以。经测试,1-8192之间的值都可以.频率代表一秒中可以执行多少次,如2048表示1秒钟执行2048次