【问题标题】:kernel module write to proc内核模块写入 proc
【发布时间】:2015-03-20 12:10:48
【问题描述】:

我已经制作了以下内核模块来在/proc目录中创建一个进程“hello_proc”:

#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>

static int hello_proc_show(struct seq_file *m, void *v) {
    seq_printf(m, "P5 : Hello proc!\n");
    return 0;
}

static int hello_proc_open(struct inode *inode, struct  file *file) {
    return single_open(file, hello_proc_show, NULL);
}

static const struct file_operations hello_proc_fops = {
    .owner = THIS_MODULE,
    .open = hello_proc_open,
    .read = seq_read,
    .write = seq_write,
    .llseek = seq_lseek,
    .release = single_release,
};

static int hello_proc_init(void) {
    proc_create("hello_proc", 0, NULL, &hello_proc_fops);
    printk("P5 : Process hello proc created");
    return 0;
}

static void hello_proc_exit(void) {
    remove_proc_entry("hello_proc", NULL);
}

MODULE_LICENSE("GPL");
module_init(hello_proc_init);
module_exit(hello_proc_exit);

我插入了模块,并在目录 /proc 中成功创建了一个 proc 文件“hello_proc”。接下来我要做的是编写命令的输出:

ls -l -t /proc | head -21 > /proc/hello_proc 

到文件“hello_proc”,然后读取。当我这样做时(以​​ root 身份):

root@anubhav-Inspiron-3421:~$ ls -l -t /proc | head -21 > /proc/hello_proc 

执行刚刚停止。

现在,我在互联网上查看了很多代码和资源,但找不到解释如何写入 proc 文件的代码和资源。 youtube 上也没有资源。

我发现写入 proc 文件的最佳方法是使用函数“create_proc_entry”创建 proc 文件的代码,这看起来相当简单,但对于较旧的内核版本,与我的不同。任何前进的建议/方向。

【问题讨论】:

    标签: c linux linux-kernel


    【解决方案1】:

    seq_write 不会像你想的那样做。它实际上就像seq_printf,只是它只写入固定数量的字节(而不是格式化输出)。 seq_xxx API 不支持写入设备。您必须单独实施。

    有关如何在读取端使用 single_open 创建可写设备的相当简单的模型,请查看 proc_pid_set_comm_operations,它实现了 /proc/&lt;pid&gt;/comm 并且还支持写入。

    另外,请注意 create_proc_entry 已被弃用,但将 create_proc_entry 更改为 proc_create 非常简单。如 Documentation/filesystems/seq_file.txt 中所述:

    -       entry = create_proc_entry("sequence", 0, NULL);
    -       if (entry)
    -               entry->proc_fops = &ct_file_ops;
    +       entry = proc_create("sequence", 0, NULL, &ct_file_ops);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 2014-02-16
      • 1970-01-01
      • 2013-02-21
      相关资源
      最近更新 更多