【这里使用的核心是4.14版本的】
1.创建驱动程序源文件Driver.c
1 #include "linux/kernel.h" 2 #include "linux/module.h" 3 #include "linux/fs.h" 4 #include "linux/init.h" 5 #include "linux/types.h" 6 #include "linux/errno.h" 7 #include "linux/uaccess.h" 8 #include "linux/kdev_t.h" 9 10 #define MAX_SIZE 1024 11 12 int my_open(struct inode *inode, struct file *file); 13 int my_release(struct inode *inode, struct file *file); 14 ssize_t my_read(struct file *file, char __user *user, size_t t, loff_t *f); 15 ssize_t my_write(struct file *file, const char __user *user, size_t t, loff_t *f); 16 17 char message[MAX_SIZE] = "this is arafat(very shuai boy)'s Drive"; //打开设备时会显示的消息 18 int device_num;//设备号 19 char* devName = "Driver";//设备名 20 21 struct file_operations pStruct = 22 { 23 open:my_open, 24 release:my_release, 25 read:my_read, 26 write:my_write, 27 }; 28 29 /* 注册 */ 30 int init_module() 31 { 32 int ret; 33 34 ret = register_chrdev(0, devName, &pStruct); 35 if (ret < 0) 36 { 37 printk("failed to register_chrdev.\n"); 38 return -1; 39 } 40 else 41 { 42 printk("the lgsDrive has been registered!\n"); 43 printk("id: %d\n", ret); 44 device_num = ret; 45 46 return 0; 47 } 48 } 49 50 //注销 51 void cleanup_module() 52 { 53 unregister_chrdev(device_num, devName); 54 printk("unregister successful.\n"); 55 } 56 57 58 //打开 59 int my_open(struct inode *inode, struct file *file) 60 { 61 printk("open lgsDrive OK!\n"); 62 try_module_get(THIS_MODULE); 63 return 0; 64 } 65 66 //关闭 67 int my_release(struct inode *inode, struct file *file) 68 { 69 printk("Device released!\n"); 70 module_put(THIS_MODULE); 71 72 return 0; 73 } 74 75 76 //读设备里的信息 77 ssize_t my_read(struct file *file, char __user *user, size_t t, loff_t *f) 78 { 79 if(copy_to_user(user,message,sizeof(message))) 80 { 81 return -2; 82 } 83 return sizeof(message); 84 } 85 86 //向设备里写信息 87 ssize_t my_write(struct file *file, const char __user *user, size_t t, loff_t *f) 88 { 89 if(copy_from_user(message,user,sizeof(message))) 90 { 91 return -3; 92 } 93 return sizeof(message); 94 }
2.同目录创建Makefile
1 obj-m := Driver.o #这里是上面所创建的c文件名.o 2 PWD := $(shell pwd) 3 KERNELDIR := /usr/src/linux-4.14 #你要安装mod的内核版本 4 all: 5 make -C $(KERNELDIR) M=$(PWD) modules 6 7 8 .PHONY: clean 9 clean: 10 rm -rf *.o *~ core *.ko *.mod.c modules.order Module.symvers
3.切换到root 权限
make
insmod Driver.ko【文件名是上面用的】 安装模块
4.增加自己的模块
mknod /dev/Driver c 243 0 //243为设备号 Driver是设备名
到这里就结束了 可以写个程序来验证自己程序正确性
5.移除模块
rm /dev/Driver
rmmod Driver