Writing simplest kernel module: Hello World

Hello World: The simplest module


#include      /* Needed by all modules */
#include      /* Needed for KERN_INFO */
#include        /* Needed for the macros */


static int __init module_main(void)
{
    printk(KERN_INFO "Hello world\n");
    printk(KERN_INFO "The value of the command line argument is : %d\n",myint);
    return 0;
}

static void __exit module_end(void)
{
    printk(KERN_INFO "Module Unloaded\n");
}

void hello_export(void){
   printk(KERN_INFO "I can be invoked from other modules\n");
}

MODULE_PARM(myint, int);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jyotishkar Dey");
MODULE_DESCRIPTION("A simple Hello world LKM!");
MODULE_VERSION("1.0");
EXPORT_SYMBOL(hello_export);

module_init(module_main);
module_exit(module_end);

#insmod myMod.ko myint=10
#dmesg -c
Hello World
The value of the command line argument is :10
#Module unloaded

After compiling this code a .ko object (kernel object) will be generated. To work with kernel modules you must have root privilege. After entering into root privilege
use "insmod module_name.ko myint=10" to push your module to the kernel. Remeber, linux kernel is monolithic.

The print will be seen in dmesg log. To see it use the command dmesg. There are several log levels for printk viz, EMERG >ALERT >CRIT>ER >WARN>INFO in order of priorities.

Whatever you specify insidmodule_init(), module_init that will the first function of your module that will be executed. Think of it as the main function. Generally, initialization stuffs are put here.

Now when you  "rmmod module_name.ko" , your module will be unloaded. Whatever function you specify inside module_exit(), it will the last function that is executed. Thus cleanup related logic can be put there.
You can use printk function somewhat like printf, the difference is that all the logs will be shown on dmesg log.


You can write several kernel modules each of which may depend upon one another.
In that case, if you use modprobe instead of insmod it will resolve the dependency tree and insert modules in order of dependencies. Thus if A depends upon B and B depends upon C, then C will be inserted first, followed by B and finally A. insmod, modprobe are actually short links to the kernel which actually loads the module.

Kernel module talks with each other by exporting non-static function. Whatever symbol you specify inside EXPORT_SYMBOL macro , that will be available for other modules to use. Thus other modules can use hello_export function.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.