如何在Linux内核模块中设置字符设备的模式?

问题描述 投票:0回答:1

我正在创建一个玩井字游戏的角色设备模块。我正在尝试对其进行编程,因此它将其从/dev/ticactoe模式设置为666,而不是让用户使用chmod命令。

[我的main.c包含以下内容以及tictactoeinitexit的实现(为简洁起见,已编辑):

static dev_t device_number;
static struct cdev our_cdev;
static struct class* my_class = NULL;

static struct file_operations fops = {
.owner = THIS_MODULE,
.read = tictactoe_read,
.write = tictactoe_write,
.open = tictactoe_open,
.release = tictactoe_release,
};

我有一个tictactoe.h,其中包含以下内容:

#define MODULE_NAME "tictactoe"

int tictactoe_open(struct inode *pinode, struct file *pfile);
ssize_t tictactoe_read(struct file *pfile, char __user *buffer, size_t length, loff_t *offset);
ssize_t tictactoe_write(struct file *pfile, const char __user *buffer, size_t length, loff_t *offset);
int tictactoe_release(struct inode *pinode, struct file *pfile);

我读过umode_t,但不确定如何将其用于此模块。谁能指导我正确的方向或解释如何实现umode_t变量?任何帮助表示赞赏。

c linux-kernel linux-device-driver kernel-module device-driver
1个回答
0
投票

一旦为设备创建了类my_class,则应将->devnode字段设置为用于设置所需模式的函数。您可以在<linux/stat.h>标头中找到模式,设置为666表示rw-rw-rw-,即S_IRUGO|S_IWUGO

这里是一个例子:

static char *my_devnode(struct device *dev, umode_t *mode)
{
    if (mode != NULL)
        *mode = (umode_t)S_IRUGO|S_IWUGO;
    return NULL;
}

然后在模块的init功能中:

my_class = class_create(THIS_MODULE, "...");
if (IS_ERR(my_class)) {
    // Abort...
}

my_class->devnode = my_devnode;
© www.soinside.com 2019 - 2024. All rights reserved.