Tar*_*con 3 c device-driver kernel-module linux-device-driver linux-kernel
我正在创建一个玩井字游戏的角色设备模块。我正在尝试对其进行编程,以便将其/dev/ticactoe模式设置为666,而不是让用户使用该chmod命令。
我的main.c包含以下内容以及和tictactoe的实现(为了简洁而进行了编辑):initexit
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,
};
Run Code Online (Sandbox Code Playgroud)
我有一个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);
Run Code Online (Sandbox Code Playgroud)
我读过有关 的内容umode_t,但我不确定如何将其用于此模块。谁能引导我走向正确的方向或解释如何实现该umode_t变量?任何帮助表示赞赏。
当您有疑问时,内核源代码/dev/{null,zero,...}是寻找此类内容的好地方,看看它是如何在drivers/char/mem.c.
为您的设备创建类后my_class,您应该将该->devnode字段设置为一个函数来设置您想要的模式。您可以在标题中找到模式<linux/stat.h>,设置为666means 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;
}
Run Code Online (Sandbox Code Playgroud)
然后在你的模块init函数中:
my_class = class_create(THIS_MODULE, "tictactoe");
if (IS_ERR(my_class)) {
// Abort...
}
my_class->devnode = my_class_devnode;
Run Code Online (Sandbox Code Playgroud)
哦,顺便说一句,您不需要#define MODULE_NAME,它已经自动定义了,并且是KBUILD_MODNAME.