Adding Hello World Kernel Module

In this section, you are going to learn

How to write kernel module ?

How to write Makefile for kernel module ?

How to load the kernel module ?

How to unload the kernel module ?

How to check the output the kernel module ?

Let us answer few basic questions about kernel modules

What is Kernel ?

What is use of Kernel Module ?

How to load the kernel module into Linux Kernel ?

How to unload the kernel module from Linux Kernel ?

How to check whether the kernel module is loaded or not?

How to check the output of the kernel module ?

What modinfo command does ?

What is MODULE_LICENSE ?

What is MODULE_AUTHOR ?

What is MODULE_DESCRIPTION ?

What is MODULE_VERSION ?

Let us now explore it in depth !

 1#include <linux/init.h>
 2#include <linux/module.h>
 3
 4MODULE_LICENSE("GPL");
 5MODULE_AUTHOR("ABC");
 6MODULE_DESCRIPTION("A simple hello world kernel module");
 7MODULE_VERSION("0.1");
 8
 9static int __init hello_init(void)
10{
11	printk(KERN_INFO "Hello, World module loaded\n");
12	return 0;
13}
14
15static void __exit hello_exit(void)
16{
17	printk(KERN_INFO "Hello, World module unloaded\n");
18}
19
20module_init(hello_init);
21module_exit(hello_exit);
make -C /lib/modules/$(uname -r)/build M=$(PWD) modules
sudo insmod ./helloworld.ko
$ dmesg
[10472.955996] Hello, World module loaded
$ lsmod | grep helloworld
helloworld             16384  0
$ sudo rmmod ./helloworld
$ dmesg
[10516.629413] Hello, World module unloaded
 1#include <linux/init.h>
 2#include <linux/module.h>
 3
 4MODULE_LICENSE("GPL");
 5MODULE_AUTHOR("ABC");
 6MODULE_DESCRIPTION("A simple hello world kernel module");
 7MODULE_VERSION("0.1");
 8
 9static int __init hello_init(void)
10{
11	printk(KERN_INFO "Hello, World module loaded\n");
12	return 0;
13}
14
15static void __exit hello_exit(void)
16{
17	printk(KERN_INFO "Hello, World module unloaded\n");
18}
19
20module_init(hello_init);
21module_exit(hello_exit);
1obj-m += helloworld.o
2
3all:
4	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
5
6clean:
7	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
make
sudo insmod ./helloworld.ko
$ dmesg
[10472.955996] Hello, World module loaded
$ lsmod | grep helloworld
helloworld             16384  0
$ sudo rmmod ./helloworld
$ dmesg
[10516.629413] Hello, World module unloaded