Linux字符设备驱动程序的编写框架
[11-20 15:54:01] 来源:http://www.88dzw.com arm嵌入式 阅读:8269次
文章摘要:#include <linux/fs.h> 文件系统使用相关的头文件#include <linux/mm.h>#include <linux/errno.h>#include <asm/segment.h>unsigned int test_major = 0;static int read_test(struct inode *inode,struct file *file,char *buf,int count){int left; 用户空间和内核空间if (verify_area(VERIFY_WRITE,buf,count) == -EF
Linux字符设备驱动程序的编写框架,标签:arm嵌入式系统,arm系统,http://www.88dzw.com#include <linux/fs.h> 文件系统使用相关的头文件
#include <linux/mm.h>
#include <linux/errno.h>
#include <asm/segment.h>
unsigned int test_major = 0;
static int read_test(struct inode *inode,struct file *file,char *buf,int count)
{
int left; 用户空间和内核空间
if (verify_area(VERIFY_WRITE,buf,count) == -EFAULT )
return -EFAULT;
for(left = count ; left > 0 ; left--)
{
__put_user(1,buf,1);
buf++;
}
return count;
}
这个函数是为read调用准备的。当调用read时,read_test()被调用,它把用户的缓冲区全部写1。buf 是read调用的一个参数。它是用户进程空间的一个地址。但是在read_test被调用时,系统进入核心态。所以不能使用buf这个地址,必须用__put_user(),这是kernel提供的一个函数,用于向用户传送数据。另外还有很多类似功能的函数。请参考,在向用户空间拷贝数据之前,必须验证buf是否可用。这就用到函数verify_area。为了验证BUF是否可以用。
static int write_test(struct inode *inode,struct file *file,const char *buf,int count)
{
return count;
}
static int open_test(struct inode *inode,struct file *file )
{
MOD_INC_USE_COUNT; 模块计数加以,表示当前内核有个设备加载内核当中去
return 0;
}
static void release_test(struct inode *inode,struct file *file )
{
MOD_DEC_USE_COUNT;
}
这几个函数都是空操作。实际调用发生时什么也不做,他们仅仅为下面的结构提供函数指针。
struct file_operations test_fops = {?
read_test,
write_test,
open_test,
release_test,
};
设备驱动程序的主体可以说是写好了。现在要把驱动程序嵌入内核。驱动程序可以按照两种方式编译。一种是编译进kernel,另一种是编译成模块(modules),如果编译进内核的话,会增加内核的大小,还要改动内核的源文件,而且不能动态的卸载,不利于调试,所以推荐使用模块方式。
int init_module(void)
{
int result;
result = register_chrdev(0, "test", &test_fops); 对设备操作的整个接口
if (result < 0) {
printk(KERN_INFO "test: can't get major number\n");
return result;
}
if (test_major == 0) test_major = result; /* dynamic */
return 0;
}
在用insmod命令将编译好的模块调入内存时,init_module 函数被调用。在这里,init_module只做了一件事,就是向系统的字符设备表登记了一个字符设备。register_chrdev需要三个参数,参数一是希望获得的设备号,如果是零的话,系统将选择一个没有被占用的设备号返回。参数二是设备文件名,参数三用来登记驱动程序实际执行操作的函数的指针。
如果登记成功,返回设备的主设备号,不成功,返回一个负值。
void cleanup_module(void)
{
unregister_chrdev(test_major,"test");
}
在用rmmod卸载模块时,cleanup_module函数被调用,它释放字符设备test在系统字符设备表中占有的表项。
一个极其简单的字符设备可以说写好了,文件名就叫test.c吧。
下面编译 :
$ gcc -O2 -DMODULE -D__KERNEL__ -c test.c –c表示输出制定名,自动生成.o文件
得到文件test.o就是一个设备驱动程序。
如果设备驱动程序有多个文件,把每个文件按上面的命令行编译,然后
ld ?-r ?file1.o ?file2.o ?-o ?modulename。
驱动程序已经编译好了,现在把它安装到系统中去。
$ insmod ?–f ?test.o
《Linux字符设备驱动程序的编写框架》相关文章
- › 基于Linux下USB主机接口设计
- › 基于嵌入式Linux的TFT LCD IP及驱动的设计
- › 基于Linux平台的FPGA驱动开发
- › Linux PC和51系列单片机串行通信的设计
- › 利用MLD自动化操作系统移植降低 Linux 的成本
- › ColdFire单片机在 Clinux上的应用
- 在百度中搜索相关文章:Linux字符设备驱动程序的编写框架
- 在谷歌中搜索相关文章:Linux字符设备驱动程序的编写框架
- 在soso中搜索相关文章:Linux字符设备驱动程序的编写框架
- 在搜狗中搜索相关文章:Linux字符设备驱动程序的编写框架