如何在Linux下实现定时器

如何在Linux下实现定时器,第1张

定时器Timer应用场景非常广泛,在Linux下,有以下几种方法:

1,使用sleep()和usleep()

其中sleep精度是1秒,usleep精度是1微妙,具体代码就不写了。使用这种方法缺点比较明显,在Linux系统中,sleep类函数不能保证精度,尤其在系统负载比较大时,sleep一般都会有超时现象。

2,使用信号量SIGALRM + alarm()

这种方式的精度能达到1秒,其中利用了*nix系统的信号量机制,首先注册信号量SIGALRM处理函数,调用alarm(),设置定时长度,代码如下:

[cpp] view plain copy

#include <stdio.h>

#include <signal.h>

void timer(int sig)

{

if(SIGALRM == sig)

{

printf("timer\n")

alarm(1) //we contimue set the timer

}

return

}

int main()

{

signal(SIGALRM, timer)//relate the signal and function

alarm(1) //trigger the timer

getchar()

return 0

}

alarm方式虽然很好,但是无法首先低于1秒的精度。

3,使用RTC机制

RTC机制利用系统硬件提供的Real Time Clock机制,通过读取RTC硬件/dev/rtc,通过ioctl()设置RTC频率,代码如下:

[cpp] view plain copy

#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)

if(fd <0)

{

perror("open")

exit(errno)

}

/*Set the freq as 4Hz*/

if(ioctl(fd, RTC_IRQP_SET, 1) <0)

{

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)

}

for(i = 0i <100i++)

{

if(read(fd, &data, sizeof(unsigned long)) <0)

{

perror("read")

close(fd)

exit(errno)

}

printf("timer\n")

}

/* Disable periodic interrupts */

ioctl(fd, RTC_PIE_OFF, 0)

close(fd)

return 0

}

这种方式比较方便,利用了系统硬件提供的RTC,精度可调,而且非常高。

4,使用select()

这种方法在看APUE神书时候看到的,方法比较冷门,通过使用select(),来设置定时器;原理利用select()方法的第5个参数,第一个参数设置为0,三个文件描述符集都设置为NULL,第5个参数为时间结构体,代码如下:

[cpp] view plain copy

#include <sys/time.h>

#include <sys/select.h>

#include <time.h>

#include <stdio.h>

/*seconds: the secondsmseconds: the micro seconds*/

void setTimer(int seconds, int mseconds)

{

struct timeval temp

temp.tv_sec = seconds

temp.tv_usec = mseconds

select(0, NULL, NULL, NULL, &temp)

printf("timer\n")

return

}

int main()

{

int i

for(i = 0 i <100i++)

setTimer(1, 0)

return 0

}

这种方法精度能够达到微妙级别,网上有很多基于select()的多线程定时器,说明select()稳定性还是非常好。

总结:如果对系统要求比较低,可以考虑使用简单的sleep(),毕竟一行代码就能解决;如果系统对精度要求比较高,则可以考虑RTC机制和select()机制。

个人解决了,以下是一个实现:

#include <stdlib.h>

#include <unistd.h>

#include <stdio.h>

#include <signal.h>

#include <string.h>

#include <pthread.h>

#include <time.h>

#if 1

pthread_attr_t attr

timer_t hard_timer, software_timer

struct sigevent hard_evp, software_evp

static void watchdog_hard_timeout(union sigval v)

{

time_t t

char p[32]

timer_t *q

struct itimerspec ts

int ret

time(&t)

strftime(p, sizeof(p), "%T", localtime(&t))

printf("watchdog hard timeout!\n")

printf("%s thread %d, val = %u, signal captured.\n", p, (unsigned int)pthread_self(), v.sival_int)

q = (timer_t *)(v.sival_ptr)

printf("hard timer_t:%d add:%p, q:%p!\n", (int)hard_timer, &hard_timer, q)

ts.it_interval.tv_sec = 0

ts.it_interval.tv_nsec = 0

ts.it_value.tv_sec = 6

ts.it_value.tv_nsec = 0

ret = timer_settime(*q, CLOCK_REALTIME, &ts, NULL)

if (ret != 0) {

printf("settime err(%d)!\n", ret)

}

}

static void watchdog_software_timeout(union sigval v)

{

time_t t

char p[32]

timer_t *q

struct itimerspec ts

int ret

time(&t)

strftime(p, sizeof(p), "%T", localtime(&t))

printf("watchdog software timeout!\n")

printf("%s thread %d, val = %u, signal captured.\n", p, (unsigned int)pthread_self(), v.sival_int)

q = (timer_t *)(v.sival_ptr)

printf("hard timer_t:%d add:%p, q:%p!\n", (int)hard_timer, &hard_timer, q)

ts.it_interval.tv_sec = 0

ts.it_interval.tv_nsec = 0

ts.it_value.tv_sec = 10

ts.it_value.tv_nsec = 0

ret = timer_settime(*q, CLOCK_REALTIME, &ts, NULL)

if (ret != 0) {

printf("settime err(%d)!\n", ret)

}

}

static void dcmi_sol_pthread_attr_destroy(pthread_attr_t *attr)

{

pthread_attr_destroy(attr)

}

static int dcmi_sol_pthread_attr_init(pthread_attr_t *attr)

{

int ret

if ((ret = pthread_attr_init(attr) != 0)) {

goto err

}

if ((ret = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)) != 0) {

dcmi_sol_pthread_attr_destroy(attr)

goto err

}

/* 设置线程的栈大小,失败则用系统默认值 */

pthread_attr_setstacksize(attr, 128 * 1024)

return 0

err:

printf("set ptread attr failed(ret:%d)!\n", ret)

return -1

}

int main(void)

{

struct itimerspec ts

int ret

ret = dcmi_sol_pthread_attr_init(&attr)

if (ret != 0) {

printf("init pthread attributes fail(%d)!\n", ret)

exit(-1)

}

memset(&hard_evp, 0, sizeof(struct sigevent))

hard_evp.sigev_value.sival_ptr = &hard_timer

hard_evp.sigev_notify = SIGEV_THREAD

hard_evp.sigev_notify_function = watchdog_hard_timeout

hard_evp.sigev_notify_attributes = NULL//&attr

memset(&software_evp, 0, sizeof(struct sigevent))

software_evp.sigev_value.sival_ptr = &software_timer

software_evp.sigev_notify = SIGEV_THREAD

software_evp.sigev_notify_function = watchdog_software_timeout

software_evp.sigev_notify_attributes = NULL//&attr

ret = timer_create(CLOCK_REALTIME, &hard_evp, &hard_timer)

if(ret != 0) {

perror("hard timer_create fail!")

exit(-1)

}

ret = timer_create(CLOCK_REALTIME, &software_evp, &software_timer)

if (ret != 0) {

timer_delete(hard_timer)

perror("software timer_create fail!")

exit(-1)

}

ts.it_interval.tv_sec = 0

ts.it_interval.tv_nsec = 0

ts.it_value.tv_sec = 6

ts.it_value.tv_nsec = 0

ret = timer_settime(hard_timer, CLOCK_REALTIME, &ts, NULL)

if(ret != 0) {

perror("hard timer_settime fail!")

timer_delete(hard_timer)

timer_delete(software_timer)

exit(-1)

}

ts.it_value.tv_sec = 10

ret = timer_settime(software_timer, CLOCK_REALTIME, &ts, NULL)

if(ret != 0) {

perror("hard timer_settime fail!")

timer_delete(hard_timer)

timer_delete(software_timer)

exit(-1)

}

while(1) {

printf("main ready sleep!\n")

sleep(15)

printf("main sleep finish!\n")

}

return 0

}

#endif


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/7147043.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-02
下一篇 2023-04-02

发表评论

登录后才能评论

评论列表(0条)

保存