linux 一个简单的字符设备驱动例子
2011-06-30 16:07:55 来源:www.gec-edu.org
先包含这些头文件
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#define BUFFERSIZE 200
#define DEVICE_MAJOR 250 /*设置一个主设备号*/
static int device_major = DEVICE_MAJOR;
定义一个与字符设备对应的结构体
struct my_cdev
{
struct cdev cdev; /*cdev结构体,与字符设备对应*/
/*下面可以定义一些与字符设备相关的数据*/
usigned char mem[BUFFERSIZE];
};
struct my_cdev *my_cdevp; /*设备结构体指针*/
int my_cdev_open( struct inode *node, struct file *filp )
{
/*将设备结构体指针赋给文件私有数据指针*/
filp->private_data = my_cdevp /*这样可以通过文件私有数据指针得到设备结构体*/
return 0;
}
int my_cdev_release( struct inode *node, struct file *filp )
{
return 0;
}
static size_t my_cdev_read( struct file *filp, char __user *buf, size_t size, loff_t *ppos )
{
unsigned long p = *ppos; /*文件当前位置*/
unsigned int count = size; /*要读取的长度*/
int ret = 0;
struct my_cdev *dev = filp->private_data; /*通过文件私有数据指针得到设备结构体,和前面的open对应*/
if ( p >= BUFFERSIZE )
return count ? -ENXIO:0;
if ( count > BUFFERSIZE - p )
count = BUFFERSIZE - p;
/*内核空间->用户空间*/
if ( copy_to_user(buf, (void *)(dev->mem + p), count) )
{
ret = -EFAULT;
}
else
{
*ppos += count;
ret = count;
}
return ret;
}
static size_t my_cdev_write( struct file *filp, const char __user *buf, size_t size, loff_t *ppos )