kthreads (1)

April 26, 2010

[Warning: This post is a backup recovery from my previous Wordpress blog. All content was automatically converted accessing a MySQL database using a Python script (details). Mostly are in Portuguese but if you are interest I can translate to English. If you found any problem dont’t hesitate to contact me in comments.]

Creating a thread at kernel-space

Now that I know that somebody at Academia reads my posts :-) I'll put code with a _little_ documentation information together. Today we will do a quick review about kernel threads or to be more precisely, a way to perform some operations in the background. Kernel threads are standard process that:

  1. Exist solely in kernel-space.
  2. Don't have an address space.
  3. Don't context switch to user-space.
  4. Are schedulable and preemptable as normal process.

And let’s see an example:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/delay.h>

static int thread3(void *unused) {

	int count3 = 0;
	while (count3 < 1000) {
		msleep(100);
		printk("Thread 3: %d\n", count3++);
	}
	return 0;
} 

static int thread2(void *unused) {

	int count2 = 0;
	while (count2 < 1000) {
		msleep(10);
		printk("Thread 2: %d\n", count2++);
	}
	return 0;
}

static int __init threads_init(void)
{
	int count1;
	int ret1, ret2;

	count1 = 0;
	ret1 = kernel_thread(thread2, NULL, CLONE_FS | CLONE_FILES | CLONE_SIGHAND | SIGCHLD );
	ret2 = kernel_thread(thread3, NULL, CLONE_FS | CLONE_FILES | CLONE_SIGHAND | SIGCHLD );

	printk("-- kernel thread: module init\n");
	printk("-- kernel thread: spawning thread 1 ret=%d\n", ret1);
	printk("-- kernel thread: spawning thread 2 ret=%d\n", ret2);	

	/*
	   Don't use "long" loops on init().
	   If you uncomment the snippet below the insmod will lock until while finishes
	*/ 

	/*
	while (count1 < 1000) {
		msleep(10);
		printk("Thread 1: %d\n", count1++);
     	}
	*/

    return 0;
}

static void __exit threads_exit(void)
{
    printk("-- kernel thread: module removed\n");
}

module_init(threads_init);
module_exit(threads_exit);

MODULE_AUTHOR("Tiago Maluta <maluta@unifei.edu.br");
MODULE_DESCRIPTION("kthreads examples");
MODULE_LICENSE("GPL");

Things from code that are found in docs…

  • CLONE_FS means that parent and child share filesystem information.
  • CLONE_FILES means that parent and child open files.
  • CLONE_SIGHANDmeans that parent and child share signal handlers.

I use arbitrarilymsleep() just to allow user “see” what is happening when dumping kernel ring buffer.