3 驱动程序编写实例:具体实现
# define MYDRV_CLS_IO( 'c' ,0x01 )
//定义清存储区命令字
char mybuf[100];
//存储区域
int mydrv_major = 99;
//主设备号
devfs_handle_t dev_handle;
//保存设备文件系统的注册句柄
//第一步:编写file_operations函数
3 驱动程序编写实例:具体实现
ssize_t mydrv_read(struct file * filp, char * buf, size_t count,loff_t * f_pos); //函数声明
static ssize_t mydrv_write(struct file * filp,const char * buf,size_t count,loff_t * ppos);
static int mydrv_ioctl( struct inode * inode,struct file * file, unsigned int cmd, unsigned long arg);
int mydrv_open (struct inode * inode,struct file *filp);
int mydrv_release(struct inode * inode, struct file * filp); //函数声明
3 驱动程序编写实例:具体实现
struct file_operations mydrv_ops={
//设备函数接口
open: mydrv_open ,
//实现对设备的操作
read: mydrv_read,
write: mydrv_write,
ioctl: mydrv_ioctl,
release: mydrv_release;
};
// mydrv_read()将内核空间的mybuf中的字符串赋给用户空间的buf区
3 驱动程序编写实例:具体实现
ssize_t mydrv_read(struct file * filp, char * bur, size_t count,loff_t * f_pos)
//filp:指向设备文件的指针;f_pos:偏移量
int length = strlen(mybuf);
if(count > 99) count = 99;
//忽略大于100部分
count = length - * f_pos;
//计算字符个数的技巧
3 驱动程序编写实例:具体实现
if(copy_to_user(buf, mybuf, count) ) {
//重内核区复制到用户区
printk("error reading, copy_to_user\n”);
retum -EFAULT;
}
*f_pos += count; //下一个
retum count;
}
// mydtv_write()将用户空间的buf字符串赋给内核空间的mybuf [ ]数组中
3 驱动程序编写实例:具体实现
static ssize_t mydrv_write(struct file * filp,const char * buf, size_t count,loff_t * ppos){
int num;
num=count<100? count: 100;
if(copy_from_user(mybuf, buf, num))
//mybufbuf
return -EFAULT;
printk("mydrv_write succeed! \ n”);
return num;
}
3 驱动程序编写实例:具体实现
static int mydrv_ioctl( struct inode * inode,struct file * file, //如果传人的命令字是
unsigned int cmd, unsigned long arg){ //MYDRV-CLS则清除mybuf数组内容
switch ( cmd ){
case MYDRV_CLS:
mybuf[0] = 0x0;
return 0;
default:
return -EINVAL;
}
}
//打开mydrv设备时调用
3 驱动程序编写实例:具体实现
# define MAX_MYDRV_DEV 2
int mydrv_open (struct inode * inode,struct file *filp){ //inede:设备文件节点
unsigned int dev = MINOR(inode- >i_rdev);
if(mydrv_num)
return -1;
3 驱动程序编写实例:具体实现
if (dev > = MAX_MYDRV_DEV)
return -ENODEV;
filp- > f_ap = &mydrv_ops; //指向操作函数
printk(“open success\n”);
MOD_INC_USE_COUNT; //只是简单地加1
return 0;
}
//关闭mydrv设备,这里只是将引用次数减1
int mydrv_release(struct inode * inode, struct file * filp){
MOD_DEC_USE_COUNT;
return 0;
}
3 驱动程序编写实例:具体实现