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.


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

struct task_struct *ts;

int my_thread(void *data)

        printk("I am a kernel thread\n");
        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)




obj-m := kthread.o

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

    @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: