使用字符设备

分配设备编号后要创建该字符设备使用以下命令

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);

注册后设备就可以使用了.

使用字符设备过程: 分配编号->创建设备->激活设备->使用设备(通过系统调用)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值