5.1、cdev
//分配
struct cdev *my_cdev = cdev_alloc();
//初始化
// cdev: 待初始化的cdev结构
// fops: 设备对应的操作函数集
void cdev_init(struct cdev *cdev, const struct file_operations *fops);
//注册, 告诉内核
// dev: 添加到内核的字符设备结构
// num: 设备号
// count: 关联到设备的设备号数目,通常为1
int cdev_add(struct cdev *dev, dev_t num, unsigned count);
//去除字符设备
void cdev_del(struct cedv *);
5.2、示例代码
#include
#include
#include
#include
#include
MODULE_LICENSE("GPL");
MODULE_AUTHOR("ZZX");
static int major = 230;
static int minor = 0;
static dev_t devno;
static struct cdev cdev;
static int hello_open(struct inode *inode, struct file *ifilep)
{
printk("hello openn");
return 0;
}
static struct file_operations hello_ops =
{
.open = hello_open,
};
static int hello_init(void)
{
int result;
int error;
printk("hello_initn");
devno = MKDEV(major, minor);
result = register_chrdev_region(devno, 1, "dev_test");
if(result < 0){
printk("register_chrdev_region fauiln");
return result;
}
cdev_init(&cdev, &hello_ops);
error = cdev_add(&cdev, devno, 1);
if(error < 0)
{
printk("cdev_add failn");
unregister_chrdev_region(devno,1);
return error;
}
return 0;
}
static void hello_exit(void)
{
printk("hello_exitn");
cdev_del(&cdev);
unregister_chrdev_region(devno,1);
return;
}
module_init(hello_init);
module_exit(hello_exit);
mknode /dev/test c 230 0