1.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 // Version: MAJOR.MINOR
#define HELLO_MINOR 0
#define DEVICE_NAME "HelloModule"
static int hello_open(struct inode *inode, struct file *file)
{
printk(KERN_EMERG "hello open.\n");
return 0;
}
static int hello_write(struct file *file, const char __user * buf, size_t count, loff_t *ppos)
{
printk(KERN_EMERG "hello writing:%s.\n", buf);
return 0;
}
static struct file_operations hello_flops = {
.owner = THIS_MODULE,
.open = hello_open,
.write = hello_write,
};
static int __init hello_init(void){ // init_module()
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 "init_module(): enter.......\n ");
printk(KERN_EMERG DEVICE_NAME " initialized.\n");
return 0;
}
static void __exit hello_exit(void)
{ // cleanup_module()
unregister_chrdev(HELLO_MAJOR, DEVICE_NAME);
printk(KERN_EMERG "cleanup_module(): exit.......\n ");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL"); // 版权声明
2.MakeFile
ifneq ($(KERNELRELEASE),)
MODULE_NAME = hellomodule
$(MODULE_NAME)-objs := hello.o
obj-m := $(MODULE_NAME).o
else
KERNEL_DIR = /lib/modules/`uname -r`/build
MODULEDIR := $(shell pwd)
endif
.PHONY: modules
default: modules
modules:
make -C $(KERNEL_DIR) M=$(MODULEDIR) modules
clean distclean:
rm -f *.o *.mod.c .* .* .cmd *.ko
rm -rf .tmp_versions
3.进入到这俩个文件的目录下,使用命令ls可以看到这两个文件
4.使用命令make,结果因该为下图所示
5.进入root 权限,使用su root
6.使用命令ls,应该可以看到文件insmod hellomodule.ko
6.加载驱动,使用insmod hellomodule.ko
7.查看驱动是否已经加载,使用命令vi /proc/devices,如果成功加载,会如下图所示