#include
#include
#include
MODULE_LICENSE("GPL");//声明证书,必须有也可以用其他的,比如DAUL等
#define MAJOR_NUM 222 //定义主设备号为222,这里也可以让内核自动定义,现在是人工定义,需要查看已有的设备号,
//可以用cat /proc/device查看,不要重复就好
static ssize_t chardev_read(struct file *,char *,size_t,loff_t *); //这两句是声明待会用到的file_operations结构体中的函数,读写
static ssize_t chardev_write(struct file *,const char *,size_t,loff_t *);
struct file_operations chardev_fops=
{
read: chardev_read,
write: chardev_write,
};//这是一个结构体,定义chardev_fops为一个file_operations的结构体,这个是必须的,这个结构体将与下面的主设备号,设备名连接成为一个整体
static int chardev_var = 0;//随便定义了一个静态变量,用于测试而已
static int __init chardev_init(void) //这是模块的初始化函数
{
int ret;
ret = register_chrdev(MAJOR_NUM,"chardev",&chardev_fops); //注册设备,就是上面讲的将MAJOR_NUM,设备名chardev,还有chardev_fops结合
if(ret)
printk("chardev register faild...\n");
printk("chardev register succes...\n");
return ret;
}
static void __exit chardev_exit(void) //注销设备
{
unregister_chrdev(MAJOR_NUM,"chardev");//注意,此函数没有返回值
}
static ssize_t chardev_read(struct file *filp,char *buf,size_t len,loff_t *off) //这就是测试程序里面的read函数在内核里真正的执行体,
//它的作用是将内核数据写到用户空间
{
if(copy_to_user(buf,&chardev_var,sizeof(int))) //注意区分copy_to_user和copy_from_user的区别,都是以用户空间为主体的,这里的函数里面的参数具体没有看明白
//这里面的buf,是不是内核空间的一个数据缓冲区?他是不是与chardev这个设备文件有什么联系?还是他就是用户空间num的形式参数而已?
return -EFAULT;
return sizeof(int);
}
static ssize_t chardev_write(struct file *filp,const char *buf,size_t len,loff_t *off)
{
if(copy_from_user(&chardev_var,buf,sizeof(int)))
return -EFAULT;
return sizeof(int);
}
module_init(chardev_init);
module_exit(chardev_exit);
//测试程序teat1.c
#include
#include
#include
#include
main()
{
int fd,num;
fd = open("/dev/chardev1",O_RDWR,S_IRUSR | S_IWUSR);
if(fd!=-1)
{
printf("open the ‘/dev/chardev1’ success...\n");
read(fd,&num,sizeof(int));//这里我是这样理解的,fd是打开的设备文件的描述符,是不是从这个文件传递数据给用户空间的num?如果是,那么这个设备文件的数据又是从何而来?
printf("The chardev is %d\n",num);
printf("input the num you want to write...\n");
scanf("%d",&num);
write(fd,&num,sizeof(int));
read(fd,&num,sizeof(int));
printf("The chardev is %d\n",num);
close(fd);
}
else
printf("Device open faild...\n");
}
/*
疑问1
为什么在file_operations结构体里面read=chardev_read?但是两者的参数个数不一样啊,如何传递的?测试程序里面只有3个参数,而chardev_read里面需要4个参数啊?
疑问2
read函数与chardev_read函数各个参数的含义是什么?用于什么用途?
*/
gilee2012 于 2013-04-26 21:57:47发表:
read: chardev_read,
这里的read并不是你测试程序里面用到的read,中间经过了几道转换的!
cargo 于 2013-04-12 12:20:37发表:
哈哈哦
胶头滴管3 于 2012-09-04 18:24:32发表:
dingqi
hangyixiao 于 2012-09-04 15:38:18发表:
同样疑惑中。。。希望高手指点一下啊
zl870213 于 2011-08-10 14:48:08发表:
顶
stephenyong 于 2011-04-10 16:25:53发表:
4# shenhao0129
谢谢
nxzcc 于 2011-04-09 08:54:29发表:
帮顶上
stephenyong 于 2011-04-08 17:00:18发表:
请高手指点,小弟刚学,多谢多谢!{:2_98:}