Notes on how to create a kthread in a kernel module
Please refer to the following for how to create and build a loadable kernel module. [Linux] [kernel module] Build and load a simple loadable kernel module-Qiita
testmod.c
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kthread.h>
MODULE_LICENSE("MIT");
struct task_struct *k;
static void kthread_main(void)
{
schedule();
}
static int kthread_func(void* arg)
{
printk(KERN_INFO "[%s] start kthread\n", k->comm);
while (!kthread_should_stop()) {
kthread_main();
}
printk(KERN_INFO "[%s] stop kthread\n", k->comm);
return 0;
}
static int __init testmod_init(void)
{
printk(KERN_INFO "driver loaded\n");
k = kthread_run(kthread_func, NULL, "testmod kthread");
return 0;
}
static void __exit testmod_exit(void)
{
kthread_stop(k);
printk(KERN_INFO "driver unloaded\n");
}
module_init(testmod_init);
module_exit(testmod_exit);
kthread_run (3, ...)
macro with the init functionThe kthread_run (3, ...)
macro looks like this:
kthread_run
#define kthread_run(threadfn, data, namefmt, ...) \
({ \
struct task_struct *__k \
= kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \
if (!IS_ERR(__k)) \
wake_up_process(__k); \
__k; \
})
After executing kthread_create (3, ...)
, wake_up_process (1)
is executed.
For namefmt
, you can use format specifiers like printf and set thread names using variables.
kthread_should_stop ()
)schedule ()
TODO: Investigate the behavior of schedule ()
Execution example
$ sudo insmod testmod.ko
$ ps aux | head -1 && ps auwx | grep "\[testmod kthread\]"
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 28716 84.8 0.0 0 0 ? R 23:14 16:07 [testmod kthread]
$ sudo rmmod testmod.ko
$ dmesg | tail
[187744.330108] driver loaded
[187744.330326] [testmod kthread] start kthread
[187812.178718] [testmod kthread] stop kthread
[187812.178743] driver unloaded
It was confirmed that the thread was started and terminated in the kernel module. I was also able to check the thread created with the ps command,
[Linux] [kernel module] Build and load a simple loadable kernel module-Qiita [Linux] [kernel module] How to pass parameters as arguments when loading a loadable kernel module --Qiita [Linux] [kernel module] Specify / limit the execution CPU of kthread --Qiita
Implementing kernel thread looping and stopping in a kernel module-the future of humans and the web kthread_run macro --Linux memorandum ... (to table of contents) [PDF] kthreads
Recommended Posts