Linux中的定时器与休眠


=Start=

缘由:

学习需要

正文:

参考解答:

http://man7.org/linux/man-pages/man2/setitimer.2.html

在 2.4 的内核中,并没有提供 POSIX timer 的支持,要在进程环境中支持多个定时器,只能自己来实现,好在 Linux 提供了 setitimer(2) 的接口。它是一个具有间隔功能的定时器 (interval timer),但如果想在进程环境中支持多个计时器,不得不自己来管理所有的计时器。

#include <sys/time.h>
int setitimer(int which, const struct itimerval *new_value,struct itimerval *old_value);

http://man7.org/linux/man-pages/man2/timer_create.2.html

Linux 自 2.6 开始,已经开始支持 POSIX timer 所定义的定时器,它主要由下面的接口构成 :

#include <signal.h>
#include <time.h>
timer_create()
timer_settime()
timer_gettime()
timer_delete()

http://man7.org/linux/man-pages/man2/timerfd_create.2.html

Linux 提供了基于文件描述符的相关定时器接口:

#include <sys/timerfd.h> 
int timerfd_create(int clockid, int flags);
int timerfd_settime(int fd, int flags, const struct itimerspec *new_value, struct itimerspec *old_value);
int timerfd_gettime(int fd, struct itimerspec *curr_value);

除了以上3种Linux原生提供的计时器,我们还可以通过一些其它方法来达到类似的目的:

  1. 用 sleep/usleep/select 函数让进程睡眠一段时间,使用alarm定时发出一个信号,然后用signal/sigaction函数接收信号并进行特定处理;
  2. 还有那就是用 gettimeofday/difftime 等自己来计算时间间隔,然后时间到了就执行某一任务,但是这种方法效率低,所以不常用。
参考链接:

Linux 下定时器的实现方式分析
https://www.ibm.com/developerworks/cn/linux/l-cn-timers/index.html

浅析 Linux 中的时间编程和实现原理,第 1 部分: Linux 应用层的时间编程
https://www.ibm.com/developerworks/cn/linux/1307_liuming_linuxtime1/

浅析 Linux 中的时间编程和实现原理,第 3 部分: Linux 内核的工作
https://www.ibm.com/developerworks/cn/linux/1308_liuming_linuxtime3/index.html

Linux 实现定时器
https://liuliqiang.info/post/four-way-to-implement-linux-cron/
http://man7.org/linux/man-pages/man2/setitimer.2.html

计时器的原理和实现
https://objectkuan.gitbooks.io/ucore-docs/lab7/lab7_3_2_timer_implement.html

https://stackoverflow.com/questions/12764771/timers-in-linux-in-c
https://stackoverflow.com/questions/5540245/loops-timers-in-c
https://stackoverflow.com/questions/12463554/timer-library-in-c

Linux定时器的使用
http://www.cppblog.com/jerryma/archive/2012/01/31/164704.html

linux下使用select实现精确定时器
http://www.cnblogs.com/jjdiaries/p/3404380.html

=END=


《“Linux中的定时器与休眠”》 有 3 条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注