相关接口:
kthread_creat
kthread_run=kthread_creat + wake_up_process
kthread_stop
kthread_should_stop
fork
do_fork
vfork
clone
示例:
1- kthread_create
#include<linux/init.h>
#include<linux/module.h>
#include <linux/sched.h>
#include <linux/kthread.h>
#include <linux/err.h>
MODULE_LICENSE("Dual BSD/GPL");
static struct task_struct *test_task;
static int test_thread(void *data)
{
int cnt = 0;
while(!kthread_should_stop())
{
set_current_state(TASK_UNINTERRUPTIBLE);
printk("thread run cnt : %d\n", cnt);
cnt++;
schedule_timeout(HZ);
}
return 0;
}
static int hello_init(void)
{
printk(KERN_ALERT "HELLLO WORLD ENTER! \n");
test_task = kthread_create(test_thread, NULL, "test_task");
if(IS_ERR(test_task)){
pr_err("Failed to create thread.\n");
return PTR_ERR(test_task);
}
wake_up_process(test_task);
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT "HELLO WORLD EXIT! \n");
if(test_task){
printk("stop MyThread\n");
kthread_stop(test_task);
test_task = NULL;
}
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_AUTHOR("LHK");
2- kthread_run
#include<linux/init.h>
#include<linux/module.h>
#include <linux/sched.h>
#include <linux/kthread.h>
#include <linux/err.h>
MODULE_LICENSE("Dual BSD/GPL");
static struct task_struct *test_task;
static int test_thread(void *data)
{
int cnt = 0;
while(!kthread_should_stop())
{
set_current_state(TASK_UNINTERRUPTIBLE);
printk("thread run cnt : %d\n", cnt);
cnt++;
schedule_timeout(HZ);
}
return 0;
}
static int hello_init(void)
{
printk(KERN_ALERT "HELLLO WORLD ENTER! \n");
test_task = kthread_run(test_thread,NULL,"test_task");
if(IS_ERR(test_task)){
pr_err("Failed to create thread.\n");
return PTR_ERR(test_task);
}
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT "HELLO WORLD EXIT! \n");
if(test_task){
printk("stop MyThread\n");
kthread_stop(test_task);
test_task = NULL;
}
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_AUTHOR("LHK");
参考:
https://www.cnblogs.com/zhangxuechao/p/11709830.html
http://blog.sina.com.cn/s/blog_6237dcca0100gq67.html
linux内核设计与实现第3章