Timer list linux struct

How to use timers in Linux kernel device drivers?

I want to implement a counter in Linux device drivers which increments after every fixed interval of time. I want to do this with the help of timers. A sample code snippet would be very useful.

How often do you want to increment this? Why you even need this? (there are some counters here already, e.g. jiffles )

@Pat The OP is asking how to create a timer in kernel space. While setitimer sets a timer in user space.

3 Answers 3

There is a small example of how to use Linux kernel timers (included it here for convenience, comments are from myself, removed printk messages)

#include #include #include MODULE_LICENSE("GPL"); static struct timer_list my_timer; void my_timer_callback( unsigned long data ) < /* do your timer stuff here */ >int init_module(void) < /* setup your timer to call my_timer_callback */ setup_timer(&my_timer, my_timer_callback, 0); /* setup timer interval to 200 msecs */ mod_timer(&my_timer, jiffies + msecs_to_jiffies(200)); return 0; >void cleanup_module(void) < /* remove kernel timer when unloading module */ del_timer(&my_timer); return; >

My «edit queue is full», so I can’t post this fixed link to the IBM blog post: developer.ibm.com/tutorials/l-timers-list

Around Linux kernel 4.15 release, void setup_timer(timer, function, data); became obsolete with an intent to remove it completely.

Instead, now we have to use

void timer_setup( struct timer_list *timer, void (*callback)(struct timer_list *), unsigned int flags ); 

This can be found in linux/timer.h file.

Here’s a full example of module_with_timer.c

#include #include #include #include MODULE_LICENSE("GPL"); static struct timer_list my_timer; void my_timer_callback(struct timer_list *timer) < printk(KERN_ALERT "This line is printed after 5 seconds.\n"); >static int init_module_with_timer(void) < printk(KERN_ALERT "Initializing a module with timer.\n"); /* Setup the timer for initial use. Look in linux/timer.h for this function */ timer_setup(&my_timer, my_timer_callback, 0); mod_timer(&my_timer, jiffies + msecs_to_jiffies(5000)); return 0; >static void exit_module_with_timer(void) < printk(KERN_ALERT "Goodbye, cruel world!\n"); del_timer(&my_timer); >module_init(init_module_with_timer); module_exit(exit_module_with_timer); 
obj-m = module_with_timer.o # Get the current kernel version number KVERSION = $(shell uname -r) all: make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules clean: make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean 

Note: In real life programming, it is better to check the version of the kernel we are compiling for and then use an then appropriately start the timer.

Читайте также:  Оссн astra linux special edition

Источник

Оцените статью
Adblock
detector