demo: 创建一个内核线程,每隔1000毫秒打印一次my_thread running
sample.c
#include <linux/module.h>
#include <linux/kthread.h>
#include <linux/delay.h>
static int state;
static struct task_struct *my_tsk;
static int my_thread(void *args)
{
for(;;)
{
if(state == 1){
break;
}
msleep(1000);
printk("my_thread running\n");
}
return 0;
}
static int __init sample_init(void)
{
state = 0;
my_tsk = kthread_create(my_thread, NULL, "%s", "my_threaddd");
if (my_tsk){
wake_up_process(my_tsk);
}
return 0;
}
static void __exit sample_exit(void)
{
state = 1;
kthread_stop(my_tsk);
printk("my_thread stopped\n");
}
module_init(sample_init);
module_exit(sample_exit);
MODULE_AUTHOR("XXX");
MODULE_LICENSE("GPL");
Makefile:
obj-m := sample.o
KERNEL :=/usr/src/kernels/`uname -r`/
all:
make -C $(KERNEL) M=`pwd` modules
clean:
make -C $(KERNEL) M=`pwd` clean
查看内核线程:
ps -ef
结果:
root 3429 950 0 01:10 ? 00:00:00 sleep 60
root 3432 2 0 01:11 ? 00:00:00 [my_threaddd]
root 3435 2894 0 01:11 pts/0 00:00:00 ps -ef
本文档展示了如何在Linux内核中创建一个名为my_thread的kthread线程,该线程每1000毫秒会打印一次'my_thread running'。通过示例代码sample.c和Makefile,读者可以了解内核线程的创建过程。运行程序后,可以通过特定命令查看内核线程的运行状态。
481

被折叠的 条评论
为什么被折叠?



