Kthread
Topics in this section,
# |
Version |
---|---|
Freebsd |
14.1.0 |
In this program, you are going to learn
How to create the kernel thread ?
How to stop the kernel thread ?
1#include<sys/param.h>
2#include<sys/kernel.h>
3#include<sys/kthread.h>
4#include<sys/systm.h>
5#include<sys/proc.h>
6#include<sys/module.h>
7#include<sys/types.h>
8
9static struct proc *my_kproc; // pointer to the created kernel process
10static int count = 0;
11
12static void my_kthread(void *arg)
13{
14 while(count < 5)
15 {
16 printf("Kthread is running\n");
17 pause("my_kthread",hz); //sleep for 1 second
18 count++;
19 }
20 kproc_exit(0);
21}
22
23static int event_handler(struct module *module, int cmd, void *arg)
24{
25 int error = 0;
26
27 switch(cmd)
28 {
29 case MOD_LOAD:
30 printf("Module loaded\n");
31 error = kproc_create(my_kthread, NULL, &my_kproc, 0, 0, "kproc_thread");
32 if(error)
33 printf("Failed to create kernel process: %d\n", error);
34 break;
35 case MOD_UNLOAD:
36 printf("Module unloaded\n");
37 break;
38 default:
39 error = EOPNOTSUPP;
40 break;
41 }
42 return(error);
43}
44
45static moduledata_t kthread_data = {
46 "kthread_module",
47 event_handler,
48 NULL
49};
50
51DECLARE_MODULE(kthread_module, kthread_data, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
52
53
1SRCS=kthread.c
2KMOD=kthread_module
3
4.include <bsd.kmod.mk>
Run make command to compile
1$ pwd
2basic_device_drivers/kthread
3
4
5$ ls
6kthread.c Makefile
7
8
9$ make
10
11
12$ ls
13.depend.kthread.o export_syms kthread.c kthread_module.ko opt_global.h
14Makefile i386 kthread.o machine x86
Load the module using kldload
1$ kldload -v ./kthread_module.ko
2Loaded ./kthread_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 7850 cryptodev.ko
5 3 1 0xffffffff82176000 772c70 zfs.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 209c kthread_module.ko
Run dmesg command to check the kernel logs
1$ dmesg
2Module loaded
3Kthread is running
4Kthread is running
5Kthread is running
6Kthread is running
7Kthread is running
Unload the module using kldunload
1$ kldunload -v ./kthread_module.ko
2Unloading kthread_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 7850 cryptodev.ko
5 3 1 0xffffffff82176000 772c70 zfs.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 unloaded