分配设备编号后要创建该字符设备使用以下命令
mknod /dev/test c major minor
major和minor的值可以用从/proc/devices文件获取, 可以写脚本来获取
我们要使用该设备驱动就要通过系统调用, 实现系统调用接口就要用到一个数据结构file_operations
struct file_operations fops = {
.owner = THIS_MODULE,
.open = test_open,
.read = test_read,
/* ..... 其他的操作 */
};
file_operations 数据结构包含了一组函数指针, 具体参考linux/fs.h. .open代表open系统调用, .read代表read.
int test_open(struct inode *inode, struct file *filp) {
/* open系统调用的实现 */
}
描述该结构后, 在调用操作之前必须分配并且注册上述结构老的方法使用
int err;
err = register_chrdev(MAJOR(dev), "test", &fops);
上述函数直接把file_operations结构绑定到设备.
但是应该使用新方法cdev.
int err;
struct cdev *my_dev = cdev_alloc();
my_dev->ops = &fops;
cdev_init(my_dev, &fops);
/* cdev_add调用可能会失败 */
err = cdev_add(my_dev, dev/*设备号*/, 1);
if (err)
goto fail_alloc;
fail_alloc:
/* 移除字符设备 */
cdev_dev(my_dev);
注册后设备就可以使用了.
使用字符设备过程: 分配编号->创建设备->激活设备->使用设备(通过系统调用)