这个节是建立内核线程的例子(linux-3.2.36)
就是循环打印,有几个宏我说明一下
KERNEL_THREAD: 用kernel_thread()建立线程
KTHREAD_CREATE: 用kthread_create()建立线程
REALTIME_THREAD:使用fifo调度策略
CNT:打印的次数,自己玩玩吧,不多说了。
#include <linux/sched.h>
#include <linux/module.h>
//#define KERNEL_THREAD
#ifndef KERNEL_THREAD
#define KTHREAD_CREATE
#endif
#define REALTIME_THREAD
#ifdef KERNEL_THREAD
#include <asm/processor.h>
#include <linux/completion.h>
#endif
#ifdef KTHREAD_CREATE
#include <linux/kthread.h>
#endif
#define CNT 5
MODULE_LICENSE("GPL");
static int i = 0;
#ifdef KERNEL_THREAD
static DECLARE_COMPLETION(my_completion);
#endif
#ifdef KTHREAD_CREATE
static struct task_struct *thread_task = NULL;
#endif
static int noop(void *dummy)
{
printk("Thread start!\n");
#ifdef RELTIME_THREAD
struct sched_param param = {.sched_priority = 99};
sched_setscheduler(current, SCHED_FIFO, ¶m);
#endif
#ifdef KERNEL_THREAD
daemonize("mythread");
#endif
do
{
printk("current->mm = %p\n", current->mm);
printk("current->active_mm = %p\n", current->active_mm);
set_current_state(TASK_INTERRUPTIBLE);
if (i < CNT)
{
schedule_timeout(10 * HZ);
}
i++;
}while(i < CNT);
set_current_state(TASK_RUNNING);
#ifdef KERNEL_THREAD
complete(&my_completion);
#endif
return 0;
}
static int __init test_init(void)
{
i = 0;
#ifdef KERNEL_THREAD
kernel_thread(noop, NULL, CLONE_KERNEL | SIGCHLD);
#endif
#ifdef KTHREAD_CREATE
thread_task = kthread_create(noop, NULL, "my_thread");
wake_up_process(thread_task);
//thread_task->state = TASK_RUNNING;
#endif
return 0;
}
static void __exit test_exit(void)
{
i = CNT;
#ifdef KERNEL_THREAD
wait_for_completion(&my_completion);
#endif
#ifdef KTHREAD_CREATE
if (thread_task != NULL)
{
wake_up_process(thread_task);
kthread_stop(thread_task);
//yield();
}
#endif
}
module_init(test_init);
module_exit(test_exit);