编写字符驱动程序 - 读取cmos中的时间

要求:该驱动程序主设备文件名为:/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



加载模块 并查看调试信息

查看创建的设备驱动

运行测试程序


卸载驱动模块,检查模块驱动设备是否没有了


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值