使用kthread内核线程的内核模块

这里使用了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

转载于:https://www.cnblogs.com/muahao/p/6210761.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值