[LINUX] A simple kernel module
A simple kernel module(example code in LDD).
ref Linux Device Drivers
hello.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
static int hello_init(void)
{
printk(KERN_ALERT "HELLO, WORLD\n");
/* "current" gives the pid of the the proccess that calls the module function*/
printk(KERN_INFO "THE PROCCESS IS \"%s\" (pid %i)\n", current->comm, current->pid);
return 0;
}
static void hello_exit(void) { printk(KERN_ALERT "GOOD BYE WORLD\n"); }
module_init(hello_init);
module_exit(hello_exit);
/* module_init and module_exit registers the function to be called upon
* loading and unloading the kernel module
**/
/* MODULE_LICENSE is optional, GPL is recommended */
MODULE_LICENSE("GPL");
Makefile1
obj-m += hello.o
# IF THE MODULE OBJECT IS BUILT FROM MULTIPLE FILE
# e.g. f1.c, f2.c ... use the following line
# module-objs := f1.o f2,0
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
# MAKE OPTIONS:
# -C specify the directory of wop-level makefile
# here it is the kernel source directory.
# -M causes that makefile to move back into module
# source directory before trying to build the
# 'modules' target.This target, in turn, refers
# to the list of modules found in the obj-m
# variable.
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
Makefile2
# IF KERNELRELEASE is defined, we've been invoked from
# the kernel build system and can use its language.
ifneq ($(KERNELRELEASE),)
obj-m := hello.o
# Otherwise we were called directly from the command
# line; invoke the kernel build system.
else
KERNELDIR ?= /lib/modules/$(shell uname -r )/build
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
# This makefile is read twice on a typical build.
# When the makefile is invoked from the command line,
# it notices that the KERNELRELEASE variable has not
# been set. It locates the kernel source directory by
# taking advantage of the fact that the symbolic link
# "build" in the installed modules directory points
# back at the kernel build tree.
These two makefiles does the same thing in this case. The second is smarter, tho. See the comments in both.
Commands:
Command | Description |
---|---|
make | Make(compile) the module |
make clean | clear compiled files |
(sudo) insmod hello.ko | load the module |
lsmod | list the loaded modules |
rmmod hello | remove the module |
dmesg –follow | show printk outputs |