Timer : One shot
Topics in this section,
# |
Version |
---|---|
Freebsd |
14.1.0 |
In this program, you are going to learn
How to create the kernel timer ?
1#include<sys/param.h>
2#include<sys/module.h>
3#include<sys/kernel.h>
4#include<sys/systm.h>
5#include<sys/types.h>
6#include<sys/time.h>
7#include<sys/malloc.h>
8
9 // Structure to hold timer data
10static struct callout timer_callout;
11static int counter = 0;
12
13static void timer_handler(void *arg)
14{
15 counter++;
16 printf("Counter value = %d\n",counter);
17}
18
19static int event_handler(struct module *module, int event, void *arg)
20{
21
22 int e=0;
23
24 switch(event)
25 {
26 case MOD_LOAD:
27 printf("Module loaded\n");
28
29 // Initialize the callout structure
30 callout_init(&timer_callout, 1);
31
32 // Schedule the first callout (5 sec)
33 callout_reset(&timer_callout, 5 * hz, timer_handler, NULL);
34 break;
35
36 case MOD_UNLOAD:
37 printf("Module unloaded\n");
38
39 // Stop the timer
40 callout_stop(&timer_callout);
41 break;
42
43 default:
44 e = EOPNOTSUPP;
45 break;
46 }
47
48return(e);
49}
50
51static moduledata_t timer_data = {
52 "timer_module",
53 event_handler,
54 NULL
55};
56
57
58DECLARE_MODULE(timer_module, timer_data, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
59
60
1SRCS=timer.c
2KMOD=timer_module
3
4.include <bsd.kmod.mk>
5
6
1$ pwd
2basic_device_drivers/timer_one_shot
3
4
5$ ls
6timer.c Makefile
7
8
9$ make
10
11
12$ ls
13.depend.timer.o export_syms machine timer.c timer_module.ko
14Makefile i386 opt_global.h timer.o x86
Load the module using kldload
1$ kldload -v ./timer_module.ko
2Loaded ./timer_module.ko, id=8
Run kldstat command to check the loaded modules
1$ kldstat
2Id Refs Address Size Name
3 1 29 0xffffffff80200000 1f6c698 kernel
4 2 1 0xffffffff8216d000 772c70 zfs.ko
5 3 1 0xffffffff828e1000 7850 cryptodev.ko
6 4 1 0xffffffff83218000 3220 intpm.ko
7 5 1 0xffffffff8321c000 2178 smbus.ko
8 6 1 0xffffffff8321f000 3360 uhid.ko
9 7 1 0xffffffff83223000 3360 wmt.ko
10 8 1 0xffffffff83227000 20d4 timer_module.ko
Run dmesg command to check the kernel logs
1$ dmesg
2Module loaded
3Counter value = 1
Unload the module using kldunload
1$ kldunload -v ./timer_module.ko
2Unloading timer_module.ko, id=8
Run kldstat command to check the loaded modules
1$ kldstat
2Id Refs Address Size Name
3 1 27 0xffffffff80200000 1f6c698 kernel
4 2 1 0xffffffff8216d000 772c70 zfs.ko
5 3 1 0xffffffff828e1000 7850 cryptodev.ko
6 4 1 0xffffffff83218000 3220 intpm.ko
7 5 1 0xffffffff8321c000 2178 smbus.ko
8 6 1 0xffffffff8321f000 3360 uhid.ko
9 7 1 0xffffffff83223000 3360 wmt.ko
Run dmesg command to check the kernel logs
1$ dmesg
2Module loaded
3Counter value = 1
4Module unloaded