Linux Kernel Module Hello World

2015-03-16 Mithrilwoodrat 更多博文 » 博客 » GitHub »

原文链接 http://woodrat.xyz/2015/03/16/linux-kernel-module-hello-world/
注:以下为加速网络访问所做的原文缓存,经过重新格式化,可能存在格式方面的问题,或偶有遗漏信息,请以原文为准。


参考 The Linux Kernel Module Programming Guide , linux kernel hacking lessons

我在我的Debian虚拟机中尝试的kernel module的编写.

uname -a Linux localhost 3.2.0-4-486 #1 Debian 3.2.60-1+deb7u3 i686 GNU/Linux

开始的时候编译了2.6版本的内核

make menuconfig make mv /path/linux-version/arch/i386/bzImage /boot/vmlinuz-version

grup-update

重启后grub菜单中就应该有新编译的内核了,但是我启动后出现了kernel panic VFS错误, 因为发现版的内核编译选项中是支持module的,所以可以直接跳过这一步,不管错误原因,进行下面的工作.

首先安装 linux-source-$(uname -r) 然后将 /usr/src/linux-header-version-common/include/linux/ 中需要的头文件(如 module.h kernel.h等复制到 /usr/include/linux/中

然后编写我们的hello world. 命名为mymodule.c(代码来自上面的参考网站)

#include <linux/module.h>

include <linux/init.h>

static int __init mymodule_init(void) { printk ("My module worked\n"); return 0; }

static void __exit mymodule_exit(void) { printk ("Unloading my module. \n"); return; }

module_init(mymodule_init); module_exit(mymodule_exit);

MODULE_LICENSE("GPL");     然后编写Makefile

    

obj-m += mymodule.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后生产mymodule.ko

可以使用modinfo查看该模块

modinfo mymodule.ko filename: /home/woodrat/Desktop/kernel_dev/mymodule.ko license: GPL depends:
vermagic: 3.2.0-4-486 mod_unload modversions 486 使用insmod插入模块,然后dmesg | tail 查看是否成功.

insmod mymodule.ko dmesg | tail [ 3112.359212] My module worked 使用rmmod移除模块,dmesg | tail 查看是否移除

rmmod mymodule dmesg | tail [ 3223.504058] Unloading my module.