開啟linux 核心線程

來源:互聯網
上載者:User

函數說明:

 

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是不起作用的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.