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

问题描述 投票:1回答: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个回答
1
投票

不确定时,/dev/{null,zero,...}的内核源代码是查找此类内容的好地方,请看一下如何在drivers/char/mem.c中实现此代码。

一旦为设备创建了类drivers/char/mem.c,则应将my_class字段设置为用于设置所需模式的函数。您可以在->devnode标头中找到模式,将<linux/stat.h>设置为666,即rw-rw-rw-。最好在代码中的某个位置使其成为常数。

这是解决方法:

S_IRUGO|S_IWUGO

然后在模块的#define DEV_CLASS_MODE ((umode_t)(S_IRUGO|S_IWUGO)) static char *my_class_devnode(struct device *dev, umode_t *mode) { if (mode != NULL) *mode = DEV_CLASS_MODE; return NULL; } 功能中:

init

哦,顺便说一句,您不需要my_class = class_create(THIS_MODULE, "tictactoe"); if (IS_ERR(my_class)) { // Abort... } my_class->devnode = my_class_devnode; ,它已经自动定义,并且是#define MODULE_NAME

© www.soinside.com 2019 - 2024. All rights reserved.