Get in touch:
01524 851 877
07718 896 553

Simple Sleeping Linux Kernel Thread

Posted on May 26 2009 by Matthew Jakeman

I am currently implementing the timeout functionality for the NP++ kernel module. Each physical mapping has a function pointer defined in its descriptive struct (struct np_sw) as described here.

Until now this hasn’t actually been implemented but I wanted to create a kernel thread that simply sleeps for 500 milliseconds, then awakes and looks through all the physical mappings available on the system and calls their timeout function.

This is a fairly simple process but in order to achieve it we need to include a couple of new headers :

#include <linux/kthread.h>
#include <linux/delay.h>

The first of these is for the thread related functions needed and the second is to allow us to sleep the thread.

Now we have those included we need to declare a function that will be called when we start the thread as follows :

int timeout_thread(void *data)
Any kernel thread function needs ro return an int and take a void pointer as the only argument to conform with the function pointer defined the kthread_create() function in kthread.h which the kthread_run() macro is a wrapper for.

Now we need to actually create the thread. I have done this in the modules init_module() function as follows:

kthread_run(timeout_thread, NULL, "NP++ Timeout Thread");
Now this is all done we simply need to put some implementation into the timeout_thread() function to perform the sleep as follows:

//Some Code Here

This sets the state of the thread to TASK_RUNNING to tell the kernel that the thread is working. The code to call the mappings individual timeout functions will go here. Then we set the state to TASK_INTERRUPTIBLE to tell the kernel we aren’t doing anything at which point we call the msleep() function to sleep the thread for 500 milliseconds.

Compile the module and you have a nice thread that will run roughly every 500 milliseconds. If you need a longer delay that can be measured in seconds the delay.h header also defines the following function that takes the number of seconds as the only argument:

void ssleep(unsigned int seconds);

Leave a comment