Linux内核:设置通过create_device()创建的/ dev文件的权限

时间:2014-05-02 09:28:59

标签: linux permissions linux-kernel chardev

我正在制作一个小型linux模块,它是char设备的驱动程序。 在我的代码中,我创建设备类,而不是它自己的设备,因此是/ dev文件 在我的系统中创建。问题是/ dev文件只有root权限和用户 既没有读取也没有写入也没有对该文件执行权限,我想改变 / dev文件权限。

我在网上搜索了答案,我发现的是更改udev文件,但是这个 解决方案在我的情况下不起作用,因为我需要在模块加载到内核时动态更改权限。我写的模块并不总是在我的机器上运行,因此我需要它“动态”更改权限。

major_number_firewall = register_chrdev(0, device_name_firewall, &my_file_implementation_firewall);

device_class = class_create(THIS_MODULE, class_name_firewall);

log_file_device = device_create(device_class, NULL, MKDEV(major_number_firewall, MINOR_LOG), NULL, device_name_log_file);

是否有更改权限的功能?

4 个答案:

答案 0 :(得分:4)

  1. 您可以写一个小udev rules来实现这一目标。

  2. 如果要实现char设备驱动程序,请考虑使用misc_register()misc_unregister(),它是上述调用的包装器(device_create() ...)。请参阅struct miscdevice

    struct miscdevice  {
        int minor;
        const char *name;
        const struct file_operations *fops;
        struct list_head list;
        struct device *parent;
        struct device *this_device;
        const char *nodename;
        umode_t mode;
    };
    
  3. 您可以使用成员(struct miscdevice *)->mode设置适当的权限(S_IRUGO | S_IRWXUGO | S_IALLUGO | etc ...)

    希望这会有所帮助。

答案 1 :(得分:1)

我认为Rocoder的意思是首先使用

更改设备文件的权限
  

int chmod(const char * path,mode_t mode); OR int fchmod(int fd,mode_t mode);

在您的用户空间应用程序中。然后使用open()打开设备文件并执行任何操作。

还要注意:我们不能让程序chmod本身进入超级用户模式。这是为了确保没有非法程序占用系统。

答案 2 :(得分:0)

你可以试试这个

#include <sys/stat.h>

int chmod(const char *path, mode_t mode); 要么 int fchmod(int fd, mode_t mode);

/etc/udev/udev.conf,

您可以修改default_mode = "0660"

答案 3 :(得分:0)

要设置misc设备的权限,您可以使用模式字段,如下所示。

static struct miscdevice somedevice = {
    .minor  = MISC_DYNAMIC_MINOR,
    .name   = DEVICE_NAME,
    .fops   = &some_fops,
    .mode   = 0666,
};

这将设置对所有人的读/写访问权限。 要执行读/写操作,您不需要是root。

希望这有帮助。