要求:该驱动程序主设备文件名为:/dev/cmos , 主设备号位 211 ,次设备号为0
cmos.c
#include <linux/init.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/cdev.h> #include <linux/types.h> #include <linux/slab.h> //kmalloc() #include <asm/uaccess.h> //copy_from_user #include <linux/pci.h> #include <linux/module.h> #include <asm/io.h> MODULE_LICENSE("GPL") ; #define device_name "cmos" #define cmos_major 211 #define cmos_minor 0 #define CMOS_READ(addr) ({outb(0x80|addr,0x70);inb(0x71);}) #define BCD_TO_BIN(val) ((val)=((val)&15)+((val)>>4)*10) static int cmos_open(struct inode *inode, struct file *file){ return 0; } static int cmos_release(struct inode *inode, struct file *file){ return 0; } static ssize_t cmos_read(struct file *file, char *buf,size_t count, loff_t *ppos) { char d[6]; //yy/mm/dd/hh/min/sec int i; printk("cmos driver:read\n"); d[0] = CMOS_READ(9); d[1] = CMOS_READ(8); d[2] = CMOS_READ(7); d[3] = CMOS_READ(4); d[4] = CMOS_READ(2); d[5] = CMOS_READ(0); for(i=0;i<6;i++) BCD_TO_BIN(d[i]); if(count > 6) count = 6; copy_to_user(buf,d,count); return count; } static struct file_operations cmos_fops = { owner:THIS_MODULE, /* Owner *///<linux/fs.h> open:cmos_open, /* Open method */ read:cmos_read, release:cmos_release, /* Release method */ }; static int __init cmos_init(void) { printk("CMOS Driver Initialized.\n"); register_chrdev(cmos_major , device_name,&cmos_fops) ; return 0; } static void __exit cmos_exit(void) { printk("exit\n"); unregister_chrdev(cmos_major , device_name) ; } module_init(cmos_init) ; module_exit(cmos_exit) ;cmostest.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> char buf[6]; int main(int argc,char **argv) { int fd; int ret; if((fd=open("/dev/cmos",O_RDWR))<0) { printf("cmos driver open fail\n"); return -1; } ret=read(fd,buf,6); if(ret == -1) { printf("read fail\n"); return -1; } printf("CMOS tell me the time is:20%02d/%02d/%02d %02d:%02d:%02d\n",buf[0],buf[1],buf[2],buf[3],buf[4],buf[5]); close(fd); return 0; }Makefile:
ifneq ($(KERNELRELEASE),) obj-m := cmos.o else KERNELDIR ?= /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) default: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules clean: rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c rm -rf Module.* modules.* endif
加载模块 并查看调试信息
查看创建的设备驱动
运行测试程序
卸载驱动模块,检查模块驱动设备是否没有了