1、在[随意目录]创建hello.c
#include <linux/init.h>
#include <linux/module.h>
#include "common.h"
static int hello_init(void){
printk(KERN_ALERT "Hello ,modules world!\n");
return 0;
}
static void hello_exit(void){
printk(KERN_ALERT "Goodby,cruel world\n");
}
MODULE_LICENSE("Dual BSD/GPL");
module_init(hello_init);
module_exit(hello_exit);
2、在该目录下创建Makefile:
obj-m := hello.o
KSRC := /lib/modules/`uname -r`/build/
all:
make -C $(KSRC) M=`pwd` modules
3、make
make -C /lib/modules/`uname -r`/build/ M=`pwd` modules
make[1]: Entering directory `/usr/src/linux-headers-3.13.0-24-generic'
CC [M] /home/zhijian/work/fs/module_test/hello/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/zhijian/work/fs/module_test/hello/hello.mod.o
LD [M] /home/zhijian/work/fs/module_test/hello/hello.ko
make[1]: Leaving directory `/usr/src/linux-headers-3.13.0-24-generic'
4、insmod hello.ko,然后dmesg查看输出信息:
[ 8147.849908] Hello ,modules world!
5、rmmod hello,然后dmesg查看输出信息:
[ 8147.849908] Hello ,modules world!
[ 8196.753620] Goodby,cruel world
备注:
make -C $(KSRC) 就是切换到KSRC目录下make,相当于cd KSRC 然后make
其实就是到kernel源码下执行make modules,然后传递了一个M=自定义module源码路径这样的参数