Friday, June 6, 2014
11:57 AM

Teminating a kernel thread using kthread_stop

In the post "Kernel thread creation 1 " we saw how to create a kthread in linux using kthread_create. The function we used to stop the thread was kthread_stop.

But kthread_stop does not terminate the thread by itself, it waits for the thread to call do_exit or terminate itself. kthread_stop only makes sure that if the thread calls the function kthread_should_stop, then kthread_should_stop returns true.

So just by calling kthread_stop in the cleanup function we can not trerminte a thread in between unless the thread does not exit by itself. To be able to terminate a thread in between, i.e. as soon as kthread_stop is called, we need to make sure that thread keeps checking for the function kthread_should_stop.

If kthread_should_stop returns true, which happens when kthread_stop is called on the thread, then the thread should exit by calling the do_exit.

Taking the same example as in the post "Kernel thread creation 1" , we need to add the following lines of code to the thread function



Thus the thread function would look like



Thus the full code for a creating a kernel thread which will terminate on call to kthread_stop would be

kthread_terminate.c



The makefile for the module would be



compile the module and insert it



To see if the therad has been created we can use the command ps



Now if we remove the module, the thread should get terminated immediately and module removal should not wait for the thread to complete as was the case in the module where kthread_should_stop was not used in the thread function.



Related links: Kernel thread creation 1Kernel thread creation 2Kernel thread creation 3

0 comments:

Post a Comment