Adsense code (2021-10-05)

Friday, August 15, 2014

Develop Hello World of Linux Kernel Module

To create Linux Kernel Module, install the development tools:

$ sudo apt-get install gcc
$ sudo apt-get install kernel-package
$ sudo apt-get install make




Make and switch to a fold for your works. Create a c program, hello.c, and Makefile file. Please notice that both hello.c and Makefile have to be in the same folder.

hello.c
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>

static int __init hello_init(void)
{
 printk(KERN_INFO "Hello World! pid = %d\n", current->pid);
 return 0;
}

static void __exit hello_exit(void)
{
 printk(KERN_INFO "Hello Bye!\n");
}

module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Linux-Buddy: linux-buddy.blogspot.com");
MODULE_DESCRIPTION("Test Module: Hello World");
MODULE_VERSION("1.0");

Makefile
obj-m += hello.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



Make the kernel module by enter the command:
$ make

Then insert the module with:
$ sudo insmod hello.ko

You can use the dmesg to view the kermel message printed by the code printk() in c program.
$ dmesg

List installed modules:
$ lsmod

To remove the module:
$ sudo rmmod hello.ko