驱动源码
#include <linux/init.h> //定义了module_init
#include <linux/module.h> //最基本的头文件,其中定义了MODULE_LICENSE这一类宏
#include <linux/fs.h>
#include <linux/device.h> // file_operations结构体定义在该头文件中
static const char* devName = "first_driver"; // 定义设备名
static struct class *first_class;
static int dev_id = 0; //定义设备号
//定义了open函数
static int first_drv_open (struct inode *inode, struct file *file)
{
printk("open file success.\n");
return 0;
}
//定义了write函数
static ssize_t first_drv_write (struct file *file, const char __user *buf, size_t size, loff_t * ppos)
{
printk("write buf.\n");
return 0;
}
//在file_operations中注册open和write函数
static struct file_operations first_drv_fo =
{
.owner = THIS_MODULE,
//将对应的函数关联在file_operations的结构体中
.open = first_drv_open,
.write = first_drv_write,
};
//init驱动的入口函数
static int first_drv_init(void)
{
//注册设备,实际是将file_operations结构体放到内核的制定数组中,以便管理
//在register_chrdev中制定major作为主设备号
dev_id = register_chrdev(dev_id, devName, &first_drv_fo);
first_class = class_create(THIS_MODULE, devName);
device_create(first_class, NULL, MKDEV(dev_id, 0), NULL, devName);
printk("init\n");
return 0;
}
//驱动的出口函数
static void first_drv_exit(void)
{
printk("exit\n");
unregister_chrdev(dev_id, devName); //卸载设备,实际是将file_operations结构体从内核维护的相关数组中以主设备号作为索引删除
device_destroy(first_class, MKDEV(dev_id, 0));
class_destroy(first_class);
}
//内核将通过这个宏,来直到这个驱动的入口和出口函数
module_init(first_drv_init);
module_exit(first_drv_exit);
MODULE_AUTHOR("wangguoshan 20210425");
MODULE_LICENSE("GPL"); //指定协议
Makefile文件
ifneq ($(KERNELRELEASE),)
obj-m := chaDrv.o
else
KERNELDIR=/usr/src/linux-4.12.14-94.41/
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
clean:
rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versionsi
调用驱动的main文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fd;
int val = 1;
fd = open("/dev/first_driver", O_RDWR);
if (fd < 0) {
printf("open file fail\n");
return -1;
}
ssize_t ret = write(fd, &val, 4);
if (ret != 0) {
printf("write file fail, ret=%d.\n", ret);
return -2;
}
return 0;
}