如何在加载设备驱动程序的内核模块时自动在/dev 中创建设备? [英] How to create a device in /dev automatically upon loading of the kernel module for a device driver?

查看:23
本文介绍了如何在加载设备驱动程序的内核模块时自动在/dev 中创建设备?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发 Linux 设备驱动程序,作为我的第一次尝试,我正在尝试开发具有以下文件选项的字符设备驱动程序,

I am attempting to develop Linux device drivers and as my first attempt I am trying to develop a char device driver that has the following file options,

struct file_operations fops{  
.open=open_fun,  
.release=release_fun,  
.write=write_fun,  
.read=read_fun,  
};  

当我使用 insmod 加载驱动程序时,我看到 /proc/devices 在字符设备下列出了驱动程序,但我在 /中找不到它开发.Google 搜索建议使用 mknod/dev 中创建一个设备并将其与驱动程序的主要和次要相关联.但是,即使以超级用户身份执行此操作,也会导致权限被拒绝"错误.

When I load the driver using insmod, I see that /proc/devices lists the driver under char devices but I can't find it in /dev. A Google search suggested use of mknod to create a deivce in /dev and associate it with the driver's major and minor. However, an attempt to do so resulted in "Permission denied" error even when done as a super user.

我应该怎么做才能让内核模块加载时设备出现在/dev中?我尝试了旧版 (register_chrdev) 和新版 (cdev_init & cdev_add) 来注册设备,但都没有奏效.

What should I do to make the device appear in /dev when the kernel module is loaded? I tried both the older (register_chrdev) and the newer version (cdev_init & cdev_add) of registering the device but none of them works.

谢谢,
米尔

推荐答案

  • 包括头文件linux/device.hlinux/kdev_t.h

    静态结构类c_dev;

    static struct class c_dev;

    在驱动的 __init 函数中添加以下 API

    • cl = class_create(THIS_MODULE,"x");

    其中 x - 加载驱动程序时显示在/sys/class/中的名称.

    where x - Name to be displayed inside /sys/class/ when driver is loaded.

    • 使用 device_create() 内核 api 和 device_create(cl, NULL, dev, NULL, "d");

    其中 d - 要在/dev 下创建的设备文件.

    where d - device file to be created under /dev.

    其中 dev 是在使用 alloc_chrdev_region API 期间初始化的第一个设备编号的变量,用于为驱动程序动态分配主编号

    where dev is variable for the first device number that is initialized during the usage of alloc_chrdev_region API for dynamic allocation of major number for the driver

    如需进一步参考,请访问链接 http://opensourceforu.com/2011/04/character-device-files-creation-operations/

    For Further reference please go through the link http://opensourceforu.com/2011/04/character-device-files-creation-operations/

    这篇关于如何在加载设备驱动程序的内核模块时自动在/dev 中创建设备?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆