Linux一段添加字符设备驱动程序的代码,求详细注释,100分急求

1.字符设备驱动程序的代码:
#include<linux/fs.h>
#include<linux/kernel.h>
#include<linux/module.h>
#include<linux/version.h>
#include<linux/types.h>
#include<linux/errno.h>
#include<asm/segment.h>
#include<asm/uaccess.h>

MODULE_LICENSE("GPL");
static int Open_times=0;//记录打开驱动的次数
static int test_major=0;
static char *Drive_buf="This is done by wusen , cs0705.";
static char User_put[81];
static ssize_t open_drive(struct inode *ind,struct file *fip){
//函数open_drive,打开驱动
Open_times++;//打开次数加一
return 0;
}
static ssize_t release_drive(struct inode *ind,struct file *fip){
//函数release_drive,用来关闭驱动
Open_times--;//打开次数减一
return 0;
}

static ssize_t read_drive(struct file *fip,char *buffer,size_tlength,loff_t *offset){//读驱动程序的函数
int bytes_read=0;
if(!(*User_put)){//如果没用用户进行写操作
while(length&&*Drive_buf){//当没有读完的时候
put_user(*(Drive_buf++),buffer++);//将buffer缓冲区中写入字符
length--;}
put_user('\0',buffer);//将字符串结束符写入buffer中
}
else{//当用户已经写字符串的时候
while(length&&User_put[bytes_read]){//当没有读完的时候
put_user(User_put[bytes_read],buffer++);//向buffer缓冲区中写入字符
length--;
bytes_read++;//记录读进去字符的个数
}
put_user('\0',buffer);//将字符串结束符写入buffer中
}
return 0;
}

static ssize_t write_drive(struct file *fip,const char*buffer, size_t length,loff_t *offset){//写驱动的函数write_drive
int i;
for(i=0;i<length&&i<80;i++,buffer++)
get_user(User_put[i],buffer);//从buffer中写入字符到User_put中
User_put[i]='\0';//将字符串结束符写入User_put中
return 0;
}

struct file_operations fops={
.read=read_drive,
.write=write_drive,
.open=open_drive,
.release=release_drive,
};

int init_module(){//初始化函数init_module
int result;
result=register_chrdev(0,"mydrive",&fops);//注册这个驱动
if(result<0)//如果注册错误,返回值为负
return result;
if(test_major==0)test_major=result;//将返回的注册号记入test_major中
return 0;
}

void cleanup_module(){
unregister_chrdev(test_major,"mydrive");
}

2.测试驱动程序的代码
#include"fcntl.h"
#include "unistd.h"
#include "stdio.h"
#include "sys/types.h"
#include "sys/stat.h"
#include <string.h>
int main(void){
int fd;
char *buf="Is there any wrong ?";
char buf2[81];
fd=open("/dev/mydrive",O_RDWR);//打开相应的驱动
if(fd==-1) {//打开失败,提示失败信息
printf("Read error!\n");
return 0;
}
read(fd,buf2,80);//从中读取字符,放在缓冲区buf2中
puts(buf2);//显示buf2中的内容
write(fd,buf,strlen(buf));//将buf中内容写入缓冲区
read(fd,buf2,80);
puts(buf2);
return 1;
}

求给出详细注释。还有不知道这个驱动程序到底意义何在?

第1个回答  2013-03-17
这个程序相当简单,就是实现一个虚拟的字符设备驱动,并写个程序验证一下读写操作。没什么实际意义。
个人感觉注释已经写得过于详细了,不知道还该注释什么,楼主具体哪里不明白,请追问。本回答被提问者和网友采纳
第2个回答  2013-03-17
CSDN有一大推的驱动分析,学习要自己动手,那样会更好点
相似回答