假設(shè)模塊的源文件為hello.c,源碼如下:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#define HELLO_MAJOR 231
#define DEVICE_NAME "HelloModule"
static int hello_open(struct inode *inode, struct file *file)
{
printk(KERN_EMERG "hello open.\n");
return 0;
}
static ssize_t hello_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
printk(KERN_EMERG "hello write.\n");
return 0;
}
static struct file_operations hello_flops = {
.owner = THIS_MODULE,
.open = hello_open,
.write = hello_write,
};
static int __init hello_init(void)
{
int ret;
ret = register_chrdev(HELLO_MAJOR, DEVICE_NAME, &hello_flops);
if (ret < 0) {
printk(KERN_EMERG DEVICE_NAME
" can't register major number.\n");
return ret;
}
printk(KERN_EMERG DEVICE_NAME " initialized.\n");
return 0;
}
static void __exit hello_exit(void)
{
unregister_chrdev(HELLO_MAJOR, DEVICE_NAME);
printk(KERN_EMERG DEVICE_NAME " removed.\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
使用該文件編譯內(nèi)核模塊。
正常情況下,Makefile文件內(nèi)容如下:
ifneq ($(KERNELRELEASE),)
obj-m:=hello.o
$(info "2nd")
else
KDIR := /lib/modules/$(shell uname -r)/build
PWD:=$(shell pwd)
all:
$(info "1st")
make -C $(KDIR) M=$(PWD) modules
clean:
rm -f *.ko *.o *.mod .*.cmd *.symvers *.mod.c *.mod.o *.order .hello*
endif
執(zhí)行make
命令,生成hello.ko文件。
執(zhí)行sudo insmod hello.ko
命令,安裝該模塊。
執(zhí)行lsmod
命令,查看安裝的模塊。就會(huì)看到第一行的就是hello模塊。
但是,如果想自定義模塊名稱為xmodule,而不是默認(rèn)的hello,如何實(shí)現(xiàn)呢?方法如下:
在Makefile中重命名obj-m并將obj-m的依賴關(guān)系設(shè)置為原始模塊(hello)
修改后的Makefile文件內(nèi)容如下:
ifneq ($(KERNELRELEASE),)
obj-m:=xmodule.o
xmodule-objs := hello.o
$(info "2nd")
else
KDIR := /lib/modules/$(shell uname -r)/build
PWD:=$(shell pwd)
all:
$(info "1st")
make -C $(KDIR) M=$(PWD) modules
clean:
rm -f *.ko *.o *.mod .*.cmd *.symvers *.mod.c *.mod.o *.order .hello*
endif
將obj-m設(shè)置為xmodule.o,并使xmodule.o依賴于hello.o.
執(zhí)行make
命令后,生成xmodule.ko, 而不是hello.ko,
安裝命令: sudo insmod xmodule.ko
查看命令:lsmod
,就會(huì)看到被安裝名為xmodule的模塊。