/sys/kernel/debugfs/mydir/myfile 将字符串写入文件。并使用 echo "worl-6ren">
gpt4 book ai didi

linux - 对 debugfs 文件执行写函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:31:43 28 4
gpt4 key购买 nike

我尝试对 debugfs 文件执行写入功能。我希望我可以使用 echo "hello">/sys/kernel/debugfs/mydir/myfile 将字符串写入文件。并使用 echo "world">>/sys/kernel/debugfs/mydir/myfilehello 之后附加 world。我在实现中发现了两个问题。一个是如果输入字符串的长度超过缓冲区大小,echo 命令将卡住。另一个是 echo "world">>/sys/kernel/debugfs/mydir/myfile 从不附加字符串。相反,它会新建一个字符串。下面是我的实现。

#include <linux/module.h>       /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */
#include <linux/miscdevice.h>
#include <linux/uaccess.h>
#include <linux/debugfs.h>
#include <linux/fs.h>
#include <linux/sched.h>
MODULE_LICENSE("GPL");

#define BUF_SIZE 10

static char foo_buf[BUF_SIZE];
static struct dentry *debug_dir;
static struct dentry *debug_foo;

static ssize_t foo_read(struct file *file, char __user *buf, size_t count,
loff_t *f_pos)
{
return simple_read_from_buffer(buf, count, f_pos, foo_buf, sizeof(foo_buf));
}

static ssize_t foo_write(struct file *file, const char __user *buf, size_t count,
loff_t *f_pos)
{
size_t ret;

if (*f_pos > BUF_SIZE)
return -EINVAL;
ret = simple_write_to_buffer(foo_buf, sizeof(foo_buf), f_pos, buf, count);
if (ret < 0)
return ret;
foo_buf[ret] = '\0';

return ret;
}

static const struct file_operations foo_fops = {
.owner = THIS_MODULE,
.read = foo_read,
.write = foo_write,
};

static int __init debugfs_start(void)
{

pr_err("init debugfs");

debug_dir = debugfs_create_dir("mydir", NULL);
if (debug_dir == NULL) {
pr_err("debugfs create my dir failed");
return -ENOMEM;
}

debug_foo = debugfs_create_file("foo", 0744, debug_dir,
NULL, &foo_fops);
if (!debug_foo) {
debugfs_remove(debug_dir);
return -ENOMEM;
}
return 0;
}

static void __exit debugfs_end(void)
{
pr_err("exit debugfs");
debugfs_remove_recursive(debug_dir);
}

module_init(debugfs_start);
module_exit(debugfs_end);

最佳答案

One is the echo command would stuck if the length of input string is over the buffer size.

这是因为它不断重试写入文件,而每次尝试都会失败。

The other is the echo "world" >> /sys/kernel/debugfs/mydir/myfile never append the string. Instead, it new a string.

这在您的实现中是预期的。如果要附加它,则需要将新字符串添加到现有字符串中。也就是说,您需要保留字符串长度的记录。但这是不同于特定于进程的打开文件的 f_pos。

How do I identify what commands(echo > or echo >>) users will use?

所以你的意思是用户在打开文件后是否“截断”了文件? debugfs 似乎不支持搜索,但我想您可以提供您的 .open 函数以及 .llseek 函数来实现它。如果是APPEND,打开文件时需要看到文件末尾。

抱歉,我无法提供完整的代码,只能提供一些提示。

关于linux - 对 debugfs 文件执行写函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26272068/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com