我尝试对debugfs文件实现写入功能。我希望我可以使用echo "hello" > /sys/kernel/debugfs/mydir/myfile
向该文件写入一个字符串。并使用echo "world" >> /sys/kernel/debugfs/mydir/myfile
在hello
后追加world
。我在实现中发现了两个问题。一个是echo
命令会在输入字符串的长度超过缓冲区大小时卡住。另一个是echo "world" >> /sys/kernel/debugfs/mydir/myfile
从不附加字符串。相反,它新建一个字符串。以下是我的实施。对debugfs文件执行写入功能
#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);
f_pos特定于进程打开文件。比如说,你可以有多个进程打开一个文件,每个进程都有自己的f_pos。 – tristan 2014-10-09 08:34:17
如何识别用户将使用哪些命令(echo>或echo >>)? – house 2014-10-09 08:47:46
我认为 - 但我还没有证实 - 区别在于'>'应该做倒带(或者可能不是,如果它可以假设在文件的头部),而'>>'应该做一个fseek结束。 – 2017-02-09 15:59:23