相关代码在资源中下载。
mdev机制根据/sys/下的系统信息来创建设备节点。
自动创建节点的步骤:
1.入口函数中:
a.创建一个类。
b.在类下面创建一个设备。
2.出口函数中:
a.注销类下的设备。
b.销毁类。
下面是所用的函数及结构:
定义类
static struct class *first_alloc_class;
定义类下的设备
static struct class_device *first_alloc_device;
创建类
/*owner;THIS_MODULE ;name:类的名字,加载驱动程序以后会
*在/sys/class看到类的名字*/
class_create(owner,name)
创建设备
/*class:就是你已经创建的类;parent;可以直接写NULL;
*devt:可以用MKDEV(major,0);fmt;设备的名字,加载驱动程序以后
*在/sys/class/你设置的类的名字 看到设备的名字*/
struct class_device
device_create(struct class * class,struct device *parent,
dev_t devt,void *drvdata,const char *fmt,...)
设备的注销
/*dev:类下创建的设备结构体指针*/
void device_unregister(struct device *dev)
类的销毁
/*cls:你所创建的类的结构体指针*/
void class_destroy(struct class *cls)
注意:不同版本的linux内核创建类和设备的函数会有所不同的。
驱动程序:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/device.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <linux/poll.h>
static struct class *first_alloc_class;
static struct class_device *first_alloc_device;
static int major;
static int first_alloc_open(struct inode *inode,
struct file *file)
{
printk("this is a test!");
return 0;
}
static ssize_t first_alloc_write (struct file *file,
const char __user *buffer,size_t num, loff_t *ooff)
{
printk("this is a function 0f write!");
return 0;
}
/*定义一个file_operations结构体*/
static struct file_operations filrst_alloc_ops ={
.owner = THIS_MODULE,
.open = first_alloc_open,
.write = first_alloc_write,
};
/*入口函数*/
int first_alloc_init(void){
/*注册,主设备出为0,自动分配设备号*/
major = register_chrdev(0,"first_alloc_device",
&filrst_alloc_ops);
/*创建类*/
first_alloc_class = class_create(THIS_MODULE,"first_class");
/*类下创建一个设备,MKDEV将主设备号和次设备号转换成dev_t类型*/
first_alloc_device = device_create(first_alloc_class,NULL,
MKDEV(major,0),NULL,"first_alloc_device");
return 0;
}
void first_alloc_exit(void){
/*注销*/
unregister_chrdev(major,"first_alloc_device");
/*类下的设备注销*/
device_unregister(first_alloc_class);
/*类的销毁*/
class_destroy(first_alloc_class);
}
MODULE_LICENSE("GPL");
/*修饰first_alloc_init*/
module_init(first_alloc_init);
/*修饰first_alloc_exit*/
module_exit(first_alloc_exit);
测试程序:
#include<stdio.h>
#include<fcntl.h>
int main(){
int fd;
fd = open("/dev/first_alloc_device",O_RDWR);
if(fd<0){
printf("can't open /dev/first_alloc_device!");
}
}
下面就是测试了
这两节的内容都是驱动的框架,下一节将补充open,write,实现点亮led.