在内核模块中创建内核线程,内核线程执行完以后,使用rmmod卸载模块时,提示“已杀死”,然后使用lsmod查看,发现内核模块并没有被卸载,占用为-1。
但是如果在内核线程正在执行的情况下使用rmmod,就可以成功卸载这个模块。
下面是代码,内核线程的作用是每隔一秒printk一次。
struct task_struct *thr = NULL;
static int counting(void *data) {
int i = 0;
for(i=0; !kthread_should_stop() && i < 10; i++) {
printk("i = %d\n",i);
msleep(1000); /* delay 1 sec */
}
return 0;
}
static int __init print_init(void) {
printk("kernel start !\n");
thr = kthread_run(counting, NULL, "counting-thread");
if(!thr) {
printk("create kthread error ! \n");
return -ECHILD;
}
return 0;
}
static void __exit print_exit(void) {
if(!IS_ERR(thr)) {
kthread_stop(thr);
}
printk("module exit! \n");
}
module_init(print_init);
module_exit(print_exit);
我的code,
https://github.com/leesagacio...