一、Linux 内核中的 Timer
在Linux中,内核通过定时器中断来跟踪时间流。这些定时器中断是使用系统的定时硬件以固定的定时器间隔生成的。每次发生定时器中断时,内部内核计数器的值都会递增。计数器在系统启动时初始化为 0,因此它表示自上次启动以来的时钟滴答次数。
二、内核计时器的使用场景
当您想在一段时间后执行某些操作时,内核计时器是您的选择之一。这些计时器用于根据时钟滴答声在将来的特定时间安排函数的执行,并可用于各种任务。
- Polling a device by checking its state at regular intervals when the hardware can’t fire interrupts.
- The user wants to send some messages to another device at regular intervals.
- Send an error when some action didn’t happen in a particular time period.
- Etc.
三、内核计时器的API
1、核心数据结构
We need to include the <linux/timer.h>
(#include <linux/timer.h>
) in order to use kernel timers. Kernel timers are described by the timer_list structure, defined in <linux/timer.h>
:
struct timer_list {
/* ... */
unsigned long expires;
void (*function)(unsigned long);
unsigned long data;
};
The expires
field contains the expiration time of the timer (in jiffies).
On expiration, function()
will be called with the given data
value.
2、Initialize / Setup Kernel Timer
There are multiple ways to Initialize / Setup Kernel Timer. We’ll see one by one.