Function Description:
Kthread_create: Create a thread.
Struct task_struct * kthread_create (INT (* threadfn) (void * data), void * data, const char * namefmt ,...);
After a thread is created, it does not run immediately. Instead, it needs to pass the task_struct pointer returned by kthread_create () to wake_up_process () and then run the thread through this function.
Kthread_run: function used to create and start a thread:
Struct task_struct * kthread_run (INT (* threadfn) (void * data), void * data, const char * namefmt ,...);
Kthread_stop: Exit by sending a signal to the thread.
Int kthread_stop (struct task_struct * thread );
Once started, the thread will continue to run unless the thread actively calls the do_exit function, or other processes call the kthread_stop function to end the running of the thread.
However, if a thread function is processing a very important task, it will not be interrupted. Of course, if a thread function never returns and does not check the signal, it will never stop.
Code:
# 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/>}</P> <p> module_init (init_kthread); <br/> module_exit (exit_kthread ); </P> <p> module_author ("yaogang"); <br/>
The function of this kernel thread is to print a "Hello World" every second ".
It is worth mentioning that the kthread_should_stop function must be embedded in the enabled thread. Otherwise, kthread_stop does not work.