linux内核线程kthread

demo: 创建一个内核线程,每隔1000毫秒打印一次my_thread running

sample.c

#include 
#include 
#include 

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驱动入门学习笔记)