函數說明:
kthread_create:建立線程。
struct task_struct *kthread_create(int (*threadfn)(void *data),void *data,const char *namefmt, ...);
線程建立後,不會馬上運行,而是需要將kthread_create() 返回的task_struct指標傳給wake_up_process(),然後通過此函數運行線程。
kthread_run :建立並啟動線程的函數:
struct task_struct *kthread_run(int (*threadfn)(void *data),void *data,const char *namefmt, ...);
kthread_stop:通過發送訊號給線程,使之退出。
int kthread_stop(struct task_struct *thread);
線程一旦啟動起來後,會一直運行,除非該線程主動調用do_exit函數,或者其他的進程調用kthread_stop函數,結束線程的運行。
但如果線程函數正在處理一個非常重要的任務,它不會被中斷的。當然如果線程函數永遠不返回並且不檢查訊號,它將永遠都不會停止。
代碼:
#include <linux/kthread.h><br />#include <linux/module.h></p><p>#ifndef SLEEP_MILLI_SEC<br />#define SLEEP_MILLI_SEC(nMilliSec)/<br />do { /<br />long timeout = (nMilliSec) * HZ / 1000; /<br />while(timeout > 0) /<br />{ /<br />timeout = schedule_timeout(timeout); /<br />} /<br />}while(0);<br />#endif</p><p>static struct task_struct * MyThread = NULL;<br />static int MyPrintk(void *data)<br />{<br />char *mydata = kmalloc(strlen(data)+1,GFP_KERNEL);<br />memset(mydata,'/0',strlen(data)+1);<br />strncpy(mydata,data,strlen(data));<br />while(!kthread_should_stop())<br />{<br />SLEEP_MILLI_SEC(1000);<br />printk("%s/n",mydata);<br />}<br />kfree(mydata);<br />return 0;<br />}</p><p>static int __init init_kthread(void)<br />{<br />MyThread = kthread_run(MyPrintk,"hello world","mythread");<br />return 0;<br />}</p><p>static void __exit exit_kthread(void)<br />{<br />if(MyThread)<br />{<br />printk("stop MyThread/n");<br />kthread_stop(MyThread);<br />}<br />}</p><p>module_init(init_kthread);<br />module_exit(exit_kthread);</p><p>MODULE_AUTHOR("YaoGang");<br />
這個核心線程的作用就是每隔一秒列印一個“hello world”。
值得一提的是kthread_should_stop函數,我們需要在開啟的線程中嵌入該函數,否則kthread_stop是不起作用的。