这里使用了msleep(50); printk 开启其实挺大的,当我使用msleep(10);机器直接卡死了;
另外ISERR不能判断结构体的,只能判断 空指针
#cat hello.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/err.h>
MODULE_LICENSE("Dual BSD/GPL");
static struct task_struct *tsk;
static int thread_function(void *data)
{
int time_count = 0;
do {
printk(KERN_INFO "thread_function: %d times", ++time_count);
msleep(50);
}while(!kthread_should_stop());
return time_count;
}
static int hello_init(void)
{
printk(KERN_INFO "Hello, world!\n");
tsk = kthread_run(thread_function, NULL, "mythread%d", 1);
if (IS_ERR(tsk)) {
printk(KERN_INFO "create kthread failed!\n");
}
else {
printk(KERN_INFO "create ktrhead ok!\n");
}
return 0;
}
static void hello_exit(void)
{
printk(KERN_INFO "Hello, exit!\n");
if (IS_ERR(tsk)){
printk(KERN_INFO "thread function already dispear");
}else {
printk(KERN_INFO "thread function is there,let's use kthread_stop to stop it\n");
int ret = kthread_stop(tsk);
printk(KERN_INFO "stop over,thread function has run %ds\n", ret);
}
}
module_init(hello_init);
module_exit(hello_exit);
[root@xxx /home/ahao.mah/main]
#cat Makefile
obj-m := hello.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
make编译
#make
make -C /lib/modules/3.10.0-327.ali2000.alios7.x86_64/build M=/home/ahao.mah/main modules
make[1]: Entering directory `/usr/src/kernels/3.10.0-327.ali2000.alios7.x86_64'
Building modules, stage 2.
MODPOST 1 modules
make[1]: Leaving directory `/usr/src/kernels/3.10.0-327.ali2000.alios7.x86_64'
安装模块
#insmod hello.ko
卸载模块
[root@rt2m09617.sqa.tbc /home/ahao.mah/main]
#rmmod hello