Monday, March 8, 2010

Kernel Thread

This post is on how to create a simple kernel thread. Note that the idea here is to explain the kthread and hence not much importance is given to other aspects.


kthread.c




#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kthread.h>

struct task_struct *ts;

int my_thread(void *data)
{


    printk("%s\n",data);<
    while(1)
    {
        printk("I am a kernel thread\n");
        msleep(3000);
        if(kthread_should_stop()) return 0;
    }
    return -1;
}

int tinit(void)
{
    ts=kthread_run(my_thread,"message from init","MyKernelThread");
    return 0;
}

void tstop(void)
{

    kthread_stop(ts);
}

module_init(tinit);
module_exit(tstop);



Makefile



obj-m := kthread.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=`pwd` modules


clean:
    @rm -f *.ko *.o *.mod.o *.mod.c



How does it work?

It is very simple. The function kthread_run is not actually a function. It is a macro defined in include/linux/kthread.h. This macro takes care of creating and starting the kernel thread. my_thread is the function that will be run by this thread. All these are very similar to user land threads. However, there is a notable difference here. From the thread function you should keep checking if your thread is being stopped and return. This is done by calling kthread_should_stop(). If this function returns true, that means it is time for us to return. This is a nice feature as this will allow us to do some cleanup before we exit. (This is a must since, if this function does not return, your rmmod will hang). As you can see, the thread is stopped by kthread_stop call. So, what are you waiting for? Have some fun with your brand new kernel thread

No comments: