【问题标题】:Linux kernel : Setting the permissions for a /dev file that was created via create_device()Linux 内核:为通过 create_device() 创建的 /dev 文件设置权限
【发布时间】:2014-06-18 22:41:56
【问题描述】:

我正在制作一个小型 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);

有修改权限的功能吗?

【问题讨论】:

    标签: linux permissions linux-kernel chardev


    【解决方案1】:
    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;
      };
      

    您可以使用成员(struct miscdevice *)->mode 来设置相应的权限(S_IRUGO | S_IRWXUGO | S_IALLUGO | 等等...)

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

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

      更改设备文件的权限

      int chmod(const char *path, mode_t mode);或 int fchmod(int fd, mode_t 模式);

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

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

      【讨论】:

        【解决方案3】:

        你可以试试这个

        #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"

        【讨论】:

        • 您好,谢谢您的回答,但是不可能将 文件包含在内核模块中。正如我提到的,更改 udev 文件不是一种选择。
        【解决方案4】:

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

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

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

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-01-22
          • 1970-01-01
          • 2021-01-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-18
          • 1970-01-01
          相关资源
          最近更新 更多