linux內核創建線程demo

#include <linux/module.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/icmp.h>
#include <linux/sched.h>
#include <linux/kthread.h>
#include <linux/err.h>

static struct task_struct *tsk = NULL;
int thread_function(void *data)
{
    int n = 0;
    while(1)
    {
        printk("XDLXDL\n");
        ssleep(3);
        if(kthread_should_stop())  break;
    }
    return 0; 
}
static int hello_init(void)  
{  
    printk(KERN_INFO "Hello, world!\n");  

    tsk = kthread_run(thread_function, NULL, "mythread");  
    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)){  
        int ret = kthread_stop(tsk);  
        printk(KERN_INFO "thread function has run %ds\n", ret);  
    }  
}  

module_init(hello_init);  
module_exit(hello_exit);  
//Makefile
ifneq ($(KERNELRELEASE),)
#obj-m:=print_tcp.o
obj-m:=hello.o
else
PWD:=$(shell pwd)
KDIR:=/usr/lib/modules/$(shell uname -r)/build
all:
	$(MAKE) -C $(KDIR) M=$(PWD)
clean:
	rm -rf *.o *.mod.c *.ko *.symvers *.order *.markers
endif

 

發佈了83 篇原創文章 · 獲贊 19 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章