PoiNtEr->: Linux Kernel Module Programming ...Hello World!! Once Again

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

Search This Blog

Saturday, February 18, 2012

Linux Kernel Module Programming ...Hello World!! Once Again




SO Once again i am back with something on kernel module programming.
Before  moving further i must suggest you to go through my previous post  as this will help you out to easily understand things.

First I  want to clear up few concepts which i was unable to address in my last post on kernel modules.

1:Kernel modules must have at least two functions: a "start" (initialization) function called init_module() which is called when the module is insmoded into the kernel, and an "end" (cleanup) function called cleanup_module() which is called just before it is rmmoded. Actually, things have changed starting with kernel 2.3.13.

Example:


#include <linux/module.h> /* Needed by all modules */

#include <linux/kernel.h> /* Needed for KERN_INFO */



int init_module(void)

{

 printk(KERN_INFO "Hello world 1.\n");



 /*

  * A non 0 return means init_module failed; module can't be loaded.

  */

 return 0;

}



void cleanup_module(void)

{

 printk(KERN_INFO "Goodbye world 1.\n");

}





2:As of Linux 2.4, you can rename the init and cleanup functions of your modules; they no longer have to be called init_module() and cleanup_module() respectively. This is done with the module_init() and module_exit() macros. These macros are defined in linux/init.h.

Example:





#include <linux/module.h> /* Needed by all modules */

#include <linux/kernel.h> /* Needed for KERN_INFO */

#include <linux/init.h>  /* Needed for the macros */




static int __init hello_2_init(void)

{

 printk(KERN_INFO "Hello, world 2\n");

 return 0;

}




static void __exit hello_2_exit(void)

{

 printk(KERN_INFO "Goodbye, world 2\n");

}




module_init(hello_2_init);

module_exit(hello_2_exit);

// As you can see now we can easily take any name as out initial and end function// but the only thing is that we have to define it in the end




3: The macro __init and __exit are  feature of kernel 2.2 and later. Notice the change in the definitions of the init and cleanup functions. The __init macro causes the init function to be discarded and its memory freed once the init function finishes for built-in drivers, but not loadable modules. If you think about when the init function is invoked, this makes perfect sense.
For Example Check out the above Program.






4:Important Commands
a) insmod(to insert module),
example: insmod hello.ko

b) rmmod(to remove a module),
example:rmmod hello

c) dmesg(to check the output of our insert module)
example:dmesg  | tail


/* Stay tuned for more */

No comments:

Post a Comment