之前学了内核模块的编写,但是没有动手实验,这次试验才发现还是有好动东西需要学习!
我的环境是虚拟机跑centos 7
1.首先编写模块:
#include<linux/init.h>
#include<linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void)
{
printk(KERN_ALERT " Hello World enter\n");
return 0;
}
static void hello_exit(void)
{
module_exit(hello_exit);
printk(KERN_ALERT " Hello World exit\n");
}
module_init(hello_init);
MODULE_ALIAS("a simplest module");
MODULE_DESCRIPTION("A simple Hello World Module");
这里就不做解释了,代码具体可以看我 关于设备驱动的学习:http://blog.csdn.net/u012510450/article/details/78141453
2.编写Makefile 文件,因为我还没有学,所以网络上copy 别人的,目前只是看得懂。
ifneq ($(KERNELRELEASE),)
#kbuild syntax. dependency relationshsip of files and target modules are listed here.
mymodule-objs := hello.o
obj-m := hello.o
else
PWD := $(shell pwd)
$(MAKE) -C $(KDIR) M=$(PWD)
KVER ?= $(shell uname -r)
KDIR := /lib/modules/$(KVER)/build
all:
clean:
endif
rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions
这里要注意的是两点,否则可能报错【Makefile missing separator. Stop】
a. ifneq 后面要有一个空格
b. all,clean 后一行的指令前面要加tab
3.保存后make一下
这时候我的错误提示:linux/module.h: No such file or directory
这是缺少内核头文件:安装一下,sudo yum install kernel-headers
其他安装教程在:http://blog.csdn.net/u012510450/article/details/78141522
然后就ok了
4.运行模块
sudo insmod hello.ko
查看系统
dmesg
或者使用lsmod (查看所有模块)
我用的是 lsmod | grep ‘hello’
移除模块
sudo rmmod hello
好哒,大功告成,开熏,中间好几次报错,主要makefile不会写,接下来要学好Makefile
参考:
http://blog.csdn.net/pottichu/article/details/1892245
http://blog.csdn.net/l_in12/article/details/49640833
http://blog.csdn.net/zaijzhgh/article/details/29918721
1.