Linux设备驱动程序系列(二) 字符设备驱动程序(1)

Download this MP3 - (Right Click)

伴着音乐开始Linux设备驱动之旅,接下来几篇日志都将记录“字符设备驱动程序”的编写与测试。

我选择边贴代码边说明的方式来进行分析设计我们的驱动程序,因为这样比较明确清楚。

自定义头文件demo.h如下:


#ifndef _DEMO_H_
#define _DEMO_H_

#include <linux/ioctl.h> /* needed for the _IOW etc stuff used later */

/********************************************************
 * Macros to help debugging
 ********************************************************/
#undef PDEBUG             /* undef it, just in case */
#ifdef DEMO_DEBUG
#ifdef __KERNEL__
#    define PDEBUG(fmt, args...) printk( KERN_DEBUG "DEMO: " fmt, ## args)
#else//usr space
#    define PDEBUG(fmt, args...) fprintf(stderr, fmt, ## args)
#endif
#else
#  define PDEBUG(fmt, args...) /* not debugging: nothing */
#endif

#undef PDEBUGG
#define PDEBUGG(fmt, args...) /* nothing: it's a placeholder */

//设备号
#define DEMO_MAJOR 224
#define DEMO_MINOR 0
#define COMMAND1 1
#define COMMAND2 2

//设备结构
struct DEMO_dev 
{
	struct cdev cdev;	  /* Char device structure		*/
};

//函数申明
ssize_t DEMO_read(struct file *filp, char __user *buf, size_t count,
                   loff_t *f_pos);
ssize_t DEMO_write(struct file *filp, const char __user *buf, size_t count,
                    loff_t *f_pos);
loff_t  DEMO_llseek(struct file *filp, loff_t off, int whence);
int     DEMO_ioctl(struct inode *inode, struct file *filp,
                    unsigned int cmd, unsigned long arg);


#endif /* _DEMO_H_ */

这里面比较需要说明的是

   1:  #define DEMO_MAJOR 224 
   2:  #define DEMO_MINOR 0
这里分别为主设备号、次设备号的定义。至于主次设备号的用处一会在源代码里面解释,这里提醒一下。
下面有很多的函数声明,这些函数是写驱动程序都应该有的,接下来解释具体实现。
下面为源文件demo.c
   1:  #include <linux/module.h>
   2:  #include <linux/kernel.h>
   3:  #include <linux/fs.h>
   4:  #include <linux/errno.h>
   5:  #include <linux/types.h>
   6:  #include <linux/fcntl.h>
   7:  #include <linux/cdev.h>
   8:  #include <linux/version.h>
   9:  #include <linux/vmalloc.h>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值