我正在制作一个小型linux模块,它是一个字符设备的驱动程序。在我的代码中,我创建了设备类,而不是设备本身,因此是/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);
是否有更改权限的功能?
-
你可以写一个小的udev规则来实现这个
-
如果您正在实现字符设备驱动程序,那么考虑使用
misc_register()
和misc_unregister()
,这是对上述调用(device_create()
…)的包装。参考struct miscdevicestruct 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 |等等…)
我认为Rocoder的意思是首先使用
更改设备文件的权限int chmod(const char *path, mode_t mode);OR int fchmod(int fd, mode);
在用户空间应用程序中。然后使用open()打开设备文件并执行任何操作。
也注意:我们不能让一个程序在自身内部chmod到超级用户模式。这是为了确保没有非法程序控制系统。
你可以试试这个
#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"
要设置misc设备的权限,可以使用mode字段,如下所示。
static struct miscdevice somedevice = {
.minor = MISC_DYNAMIC_MINOR,
.name = DEVICE_NAME,
.fops = &some_fops,
.mode = 0666,
};
将读写权限设置为all。执行读写操作不需要root权限