1.kernel thread是否只有在kernel thred中才被建立?
2.kernel thread無法被kill?
3.在module中建立的kernel thread,用kernel_thread函數,獲得的current->mm為什麼不為0 ?
4.
先看一段代碼:
#include <linux/kernel.h>
#include <linux/module.h>
static pid_t thread_pid;
static struct completion thread_exited;
static int noop(void *dummy)
{
daemonize("mythread");
allow_signal(SIGTERM);
while (!signal_pending (current)) {
/* do something else */
schedule();
}
complete_and_exit(&thread_exited, 1);
}
static int test_init(void)
{
init_completion(&thread_exited);
thread_pid = kernel_thread(noop, NULL, CLONE_KERNEL | SIGCHLD);
return 0;
}
static void test_exit(void)
{
kill_proc (thread_pid, SIGTERM, 1);
wait_for_completion(&thread_exited);
}
module_init(test_init);
module_exit(test_exit);
回答問題:
1.從上面的例子中可以看到,kernel thread的建立不一定要在kernel thread中。
2.在insmod上面的module之後,killall mythread 當然可以殺死這個kernel thread。
3.從上面的printk函數的輸出我們已經看到 current->mm 確實是為0的,毫無疑問。
但是,mm不為0的原因在哪裡呢?
kernel thread中沒有調用daemonize()函數,該函數給kernel thread 命名,並且會掛入kthread線程的列隊上去。當mm輸出不為0的時候其實輸出的mm指向的是insmod的mm
總結:
kernel_thread建立,在執行函數裡面必須用daemonize釋放資源並掛到init下。
kthread_create是比較正牌的建立函數,這個不必要調用daemonize,用這個建立的kernel thread都掛在了kthread線程下。