Sunday, June 17, 2012

Hello Driver

So, let's start building some simple modules .....

1:  #include <linux/init.h>                    //specify initialization and cleanup functions 
2:  #include <linux/module.h>             //definitions of symbols and functions 
3:  static int hello_module_init(void) 
4:  { 
5:       printk("Insert Module\n"); 
6:       return 0; 
7:  } 
8:  static void int hello_module_exit(void) 
9:  { 
10:       printk("Exit Module\n"); 
11: } 
12: module_init(helllo_moddule_init); 
13: module_exit(hello_module_exit);  
14: MODULE_LICESNSE(“GPL”); 

This module has two functions namely ‘hello_module_init’ and ‘hello_module_exit’. When the module is inserted to the kernel, hello_module_init function will be invoked. When  the module is removed from the kernel hello_module_exit function is invoked.

Here you will find some functions that are defined in the Linux kernel. ‘printk’ is such a function and it has a same behavior like the ‘printf’ function in the standard C library. One main usage of having such ‘printk’ statements is that we can check whether the module is properly inserted to (or removed from) the kernel or not.

MODULE _LICENSE is a special macro that is used to indicate that the module bears a free license. (macro - a code segment)

Let’s see the procedure of inserting the module to the kernel.
First we have to ‘make’ the file and generate .ko file
  • Create a simple text file which says ‘obj-m := hello.o’ and save it as Makefile.
  • Go to the terminal.
  • To compile the module type the command ‘$ make –C /usr/src/<kernel_version> M=pwd modules
  • This will generate ‘hello.ko’ file.
  • To insert the module ‘# insmod hello.ko’.
  • This will print the message ‘Init Module’ to the kernel.
  • If you want to see the inserted modules, type the command ‘# lsmod’. This will list all the modules.
  • To remove the module ‘# rmmod hello’.
  • This will print the message ‘Exit Module’ to the kernel.
  • These messages are printed to the kernel log. In order to see the messages type ‘# dmesg’ . This will show the messages that we put to the kernel.

No comments:

Post a Comment