1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
//1.头文件 #include <linux/init.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/cdev.h> #define MA 500 #define MI 0 int myopen(struct inode* pinode, struct file* pfile) { printk("my dev is open\n"); return 0; } int myrelease(struct inode* pinode, struct file *pfile) { printk("my dev is close\n"); return 0; } static dev_t dev; static const char * devname ="ABC"; static const unsigned int devnum = 1; static struct cdev cdev; const static struct file_operations fops ={ .open = myopen, .release = myrelease }; //2.函数实现 static int myinit(void) { /*******************kernel内核部分*******************/ //1.注册 dev = MKDEV(MA, MI); int ret = register_chrdev_region( dev, devnum, devname ); if(ret !=0) { printk("register falid!\n"); return -1; } //2. init 个体初始化 cdev_init(&cdev, &fops); //3. add 添加个体到系统 cdev_add(&cdev, dev, devnum); printk("-------init------\n"); /*******************硬件内核部分*******************/ return 0; } static void myexit(void) { /*******************kernel内核部分*******************/ //1. del 个体从系统内移除 cdev_del(&cdev); //2.unregister 注销 unregister_chrdev_region(dev, devnum); /*******************硬件内核部分*******************/ printk("-------exit------\n"); return; } //3.注册、退出 module_init(myinit); module_exit(myexit); //4. 模块信息说明 MODULE_LICENSE("GPL"); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/************************************************************************* > File Name: main.c > Author: > Mail: > Created Time: 2018年10月15日 星期一 19时19分17秒 ************************************************************************/ /***************** 1、mknod /dev/ABC c 500 0 创建设备文件 2、 执行函数打开以及设备关闭文件 ***********************/ #include<stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() { int fd =open("/dev/ABC",O_RDONLY); sleep(3); close(fd); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#module templet ifeq ($(KERNELRELEASE),) KERNELDIR ?= ~/linux-3.14 PWD := $(shell pwd) all: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules cp -af *.ko ~/nfs/ clean: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules clean rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions Module* modules* a.out else obj-m := test.o endif |