Day -1 Hello Module (Simplest Linux module code)

in #linux6 years ago

Hi, today I would like to explain about the simplest possible Linux module code. While learning any new programming or scripting language our first code would be 'hello world', so it makes sense to write a hello world kernel code.

Check the following code, it is a simple C code with few different header files and printf is not present.

#include <linux/module.h>   //needed by all modules
#include <linux/kernel.h>   //needed for 'printk'

//constructor, module entry
int init_modules(void){
//  printk (KERN_INFO, "hello world of kernel programming\n");    //commented this line because it through warning in my PC, but this should also work
    pr_info ("hello world of kernel programming\n");
    return 0;    
}

//destructor, module exit
void cleanup_module(void){
//  printk (KERN_INFO, "Bye hello world\n");    //commented this line because it through warning in my PC, but this should also work
    pr_info ("Bye hello world\n");
}

So, I have explained almost all lines which needs to be explained.

Regarding 'printk', it quite a big topic (not that big) which I'll explain in next post.

Now coming to the point, we wrote our code but how do we execute that? Using gcc ?? No, we can't use gcc. To compile kernel codes we need to use prebuilt kernel source. So to use these kernel sources we take the help of Makefile.

Here is the simplest 'Makefile' for our simplest kernel code.

obj-m := 1_hello_simple.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

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

After this we just need to make in our terminal and our binaries will be generated.

Right now we are only concerned with '.ko' files.
To load our module (our '1_hello_simple.ko') file to our system, we use # insmod 1_hello_simple.ko (if not allowed by the system, use sudo command.

To remove the module use # rmmod 1_hello_simple.ko.

That's it for now, if everything works with exit code 0 then you are in correct path.

I can't write long posts in one stress, so regarding 'insmod', 'rmmod', 'modinfo' and how to verify if your code is loaded using 'dmesg' and also about the C code, I'll explain it in my next post.

Thanks

maxresdefault.jpg