foreword
Through hello_kernel programming to achieve the following goals:
- Kernel programming framework understanding
- Module parameter call
- function call between modules
- Use of commands related to kernel modules
Environmental preparation
There are two ways to prepare the kernel source tree:
Method 1: Download the kernel source code from kernel.org and compile it manually
Method 2: Install the kernel source tree consistent with the system version through yum
yum install -y kernel-devel-`uname -r`
After installation, there will be a source directory of the corresponding version in the /usr/src/kernels path, and /lib/modules/ uname -r
/build will point to the corresponding source directory.
Kernel programming example
There are three instances of kernel programming here:
- First look at the kernel module
- Module parameter passing
function call between modules
First look at the kernel module
kernel_hello.c
#include <linux/init.h> // module_init module_exit 宏定义
#include <linux/module.h> // MODULE_LICENSE MODULE_AUTHOR MODULE_DESCRIPTION MODULE_VERSION
/* 以下4个宏分别是许可证,作者,模块描述,模块版本 */
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("calling love");
MODULE_DESCRIPTION("hello kernel programming");
MODULE_VERSION("1.0");
/* 模块入口函数 */
static int hello_init(void)
{
printk(KERN_ALERT "hello_init() start\n"); // 内核日志输出,KERN_ALERT表示日志的级别,是个字符串
return 0;
}
/* 模块退出函数 */
static void hello_exit(void)
{
printk(KERN_ALERT "hello_exit() start\n");
}
/* 注册到内核 */
module_init(hello_init);
module_exit(hello_exit);
Makefile
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
obj-m := kernel_hello.o
all:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
clean:
rm -f *.o *.ko .*.o.d *~ .*.cmd *.mod.c *.order *.ko.* *.symvers -r .tmp_versions
KDIR: Source tree path, can also be specified directly/usr/src/kernels/2.6.32-642.13.1.el6.x86_64