PoiNtEr->: My first linux kernel module ...Hello World!!

                             Difference between a dream and an aim. A dream requires soundless sleep, whereas an aim requires sleepless efforts.

Search This Blog

Saturday, August 13, 2011

My first linux kernel module ...Hello World!!

Hi guys.Today we are going to learn something about kernels.we will install a module in our linux operating system .Before doing that i request you to please google out difference between microkernel and monolithic kernel.My question is why we are interested in kernels ???
I think very obvious answer of this question is if you know every basic thing about your system and how it is implemented then you can screw it very easily..
SO now time for little warning if your love your laptop then think before trying this ,no their is no harm ...but the probability of going something wrong is much higher because you are dealing with the Heart {core} of system .

The module_init() macro defines which function is to be called at module insertion time (if the file is compiled as a module), or at boot time: if the file is not compiled as a module the module_init() macro becomes equivalent to __initcall(), which through linker magic ensures that the function is called on boot.
The function can return a negative error number to cause module loading to fail (unfortunately, this has no effect if the module is compiled into the kernel). For modules, this is called in user context, with interrupts enabled, and the kernel lock held, so it can sleep.

This module_exit() macro defines the function to be called at module removal time (or never, in the case of the file compiled into the kernel). It will only be called if the module usage count has reached zero. This function can also sleep, but cannot fail: everything must be cleaned up by the time it returns.

Code: hello_world.c

#include <linux/kernel.h>

#include <linux/module.h>

#include <linux/init.h>

#include <linux/version.h>

MODULE_DESCRIPTION("This is a my First Test Module...!");
MODULE_AUTHOR("Vishal Mishra");

static int __init my_start_init(void){

        printk(KERN_INFO "Hello World module loaded...!\n");
        return 0;

static void __exit my_remove_exit(void){

        printk(KERN_INFO "Hello World module Un-loaded...!\n"); 




obj-m   :=      hello_world.o

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


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

Now save above code as Makefile in same folder in which hello_world.c is present.

Now you can run following commands to get information about your newly installed module

1:modinfo hello_world.ko
2:lsmod  {this command will list all installed modules in your kernel and you can check whether hello_world is their or not }

For more on linux kernel module programming check out my new post which will explain each function  used above in detail here

Tutorials - OSDev Wiki

1 comment: