1、hello 简单内核模块的编写
最近在看《linux设备驱动程序》这本书,刚看完第二章。。。。。
先介绍下环境:本地有一个ubuntu的远程服务器,版本是
~/Documents$ uname -r
3.13.0-32-generic
本来在kernel.org下载了linux4.9编译了hello的模块,但是insmod时候,报错:insmod: error inserting ‘./helloworld.ko’: -1 Invalid module format,这是因为模块基于的内核版本号和系统的内核版本号不一致 解决方法写在下面吧
hello.c
#include<linux/init.h>
#include<linux/module.h>
static int __init hello_init(void)
{
printk(KERN_ALERT "hello 0220\n");
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_ALERT "exit 0220\n");
}
MODULE_LICENSE("GPL");
module_init(hello_init);
module_exit(hello_exit);
Makefile
obj-m := hello.o
KERN := $(shell uname -r)
PWD := $(shell pwd)
default:
make -C /lib/modules/$(KERN)/build M=$(PWD) modules
clean:
rm -rf *.o *.ko *.mod.c *.mod.o *.order *.symvers
铛铛铛~~~ make -C后面的路径改成系统所在的内核源码路径就可以解决冲突的问题啦,我改了之后编译的时候还有报gcc的问题
linux/compiler-gcc6.h: No such file or directory
#include gcc_header(GNUC
这个问题就直接在原来的目录里面,新建了一个文档,复制了一份原有的文件
————————————————————————————————
这两个写好了之后就可以编译了,然后在dmesg里面会有log打印出来
2、运用module_param的简单内核模块编写
hello.c
#include<linux/init.h>
#include<linux/module.h>
static int howmany = 10;
static char *whom = "world";
module_param(howmany,int,S_IRUGO);
module_param(whom,charp,S_IRUGO);
static int __init hello_init(void)
{
printk(KERN_ALERT "hello,%d,%s\n",howmany,whom);
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_ALERT "exit 0129\n");
}
MODULE_LICENSE("GPL");
module_init(hello_init);
module_exit(hello_exit);
makefile文件可与上面的一致,不需要改动
insmod hello.ko howmany=5 whom=“happyholiday”
dmesg
[2326009.854640] hello,5,happyholiday
rmmod hello
dmesg
[2326009.854640] hello,5,happyholiday
[2326022.945290] exit 0129
over啦!
版权声明:本文为zscfa原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。