模块的源文件为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");

使用该文件编译内核模块。
正常情况下,Makefile文件内容如下:

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

执行make命令,生成hello.ko文件。
执行sudo insmod hello.ko命令,安装该模块。
执行lsmod命令,查看安装的模块。就会看到第一行的就是hello模块。

但是,如果想自定义模块名称为xmodule,而不是默认的hello,如何实现呢?方法如下:
在Makefile中重命名obj-m并将obj-m的依赖关系设置为原始模块(hello)
修改后的Makefile文件内容如下:

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设置为xmodule.o,并使xmodule.o依赖于hello.o.
执行make命令后,生成xmodule.ko, 而不是hello.ko,
安装命令: sudo insmod xmodule.ko
查看命令:lsmod,就会看到被安装名为xmodule的模块。

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/xiongxuanwen/p/14707748.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程