编写简单的内核模块及内核源码下载,内核模块Makefile编写

CentOS的内核源码默认是没有下载的,需要自己下载,首先安装linux的时候就应该知道linux的版本,我装的是Centos7的
下面查一下内核的版本,使用下面的命令

[scut_lcw@localhost lcw20150802]$ uname -r
3.10.0-229.el7.x86_64

可以去官网下载,也可以直接用yum install kernel-devel-uname -r下载
一个简单的内核模块:

#include<linux/module.h>
#include<linux/init.h>
MODULE_LICENSE("Dual BSD/GPL");
static int __init helloworld_init(void)
{
        printk("hello world
");
        return 0;
}
static void __exit helloworld_exit(void)
{
         printk(KERN_ALERT"hello world
");
}
module_init(helloworld_init);
module_exit(helloworld_exit);

MODULE_AUTHOR("LCW");
MODULE_DESCRIPTION("hello");
MODULE_VERSION("1.1");

该模块只是在加载模块和卸载模块的时候打印一些语句
下面是Makefile

target= hello
obj-m:=$(target).o
KERNELDIR=/usr/src/kernels/`uname -r`
default:
        $(MAKE) -C $(KERNELDIR) M=`pwd` modules
clean:
        rm -rf *.o *.mod.c 
        rm -rf Module.symvers .*cmd .tmp_versions *.order

KERNELDIR是内核源码的安装路径,其中M=pwd那里=号后面不能有空格,不然就会出错(我就是错这里,检查了好久)
用insmod加载内核模块,rmmod卸载内核模块。

原文地址:https://www.cnblogs.com/sigma0-/p/12630531.html