簡體   English   中英

如何在 Linux kernel 模塊中設置字符設備的模式?

[英]How to set the mode for a character device in a Linux kernel module?

我正在創建一個玩井字游戲的角色設備模塊。 我正在嘗試對其進行編程,以便將其/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變量? 任何幫助表示贊賞。

/dev/{null,zero,...}的 kernel 源代碼是尋找這類東西的好地方,當你有疑問時,看看它是如何在drivers/char/mem.c中實現的.

一旦您為您的設備創建了 class my_class ,您應該將->devnode字段設置為 function 以設置您想要的模式。 您可以在<linux/stat.h> header 中找到模式,設置為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 function:

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

my_class->devnode = my_class_devnode;

哦,順便說一句,你不需要#define MODULE_NAME ,它已經自動定義了,它是KBUILD_MODNAME

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM