1. 一切皆文件
在linux系统中,无论是普通文件、设备文件,我们都是调用同一套接口:open、read、write、ioclt…
那么,最简单的写驱动程序的办法就是在内核中实现驱动版本的open、read、write、ioctl…等操作函数。
2. 写驱动程序的步骤
- 构造
file_operations结构体,比如:struct file_operations fops;
a. 在里面填充open/read/write/ioctl等成员函数;
/* 1. create file_operations */
static const struct file_operations hello_drv = {
.owner = THIS_MODULE,
.read = hello_read,
.write = hello_write,
.open = hello_open,
.release = hello_release,
};
b.在结构体外实现这些成员函数,以hello_open为例:
static int hello_open (struct inode *node, struct file *filp)
{
printk("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
return 0;
}
- 注册
file_operations结构体(告诉内核),这样我们就可以通过应用层的系统调用函数访问到驱动程序提供的接口;
int major = register_chrdev(0, "name", &fops);//major主设备号,用来表示驱动程序相同的一类设备
- 入口函数:调用:
register_chrdev
调用的是第2步的注册函数,在入口函数中注册file_operations结构体
/* 2. register_chrdev */
/* 3. entry function */</

最低0.47元/天 解锁文章
614

被折叠的 条评论
为什么被折叠?



