【问题标题】:Kernel module get data from user space内核模块从用户空间获取数据
【发布时间】:2012-08-01 10:13:06
【问题描述】:

在不使用 netlink 和不使用可能不具备的功能(例如 debugfs)的情况下,将一些数据发送到已加载和运行的内核模块的正确方法是什么?

我希望看到一种干净且安全的方法,它应该适用于大多数内核(或者最好是所有现代内核),或者充其量是它的近似值。

要向模块发送数据的用户是root用户,数据量大概在64 kiB以下,由一系列字符串组成。

我已经考虑过尝试从模块中读取文件,这不仅由于各种原因而受到高度反对,而且很难做到。 我查看了 netlink,socket() 告诉我我的内核不支持。 我查看了 debugfs,我的内核也不支持它。

显然我可以使用不同的内核,但正如我所提到的,我想要一种正确的方法来做到这一点。如果有人可以向我展示一个简单的模块示例,该模块将只对从用户空间发送的字符串执行 printk(),那就太好了。

【问题讨论】:

    标签: linux module kernel communication


    【解决方案1】:

    ... 一个简单的模块示例,它只对从用户空间发送的字符串执行 printk(),printkm.c:

    #include <linux/module.h>
    #include <linux/proc_fs.h>
    MODULE_DESCRIPTION("printk example module");
    MODULE_AUTHOR("Dietmar.Schindler@manroland-web.com");
    MODULE_LICENSE("GPL");
    
    static
    ssize_t write(struct file *file, const char *buf, size_t count, loff_t *pos)
    {
        printk("%.*s", count, buf);
        return count;
    }
    
    static struct file_operations file_ops;
    
    int init_module(void)
    {
        printk("init printk example module\n");
        struct proc_dir_entry *entry = proc_create("printk", 0, NULL, &file_ops);
        if (!entry) return -ENOENT;
    
        file_ops.owner = THIS_MODULE,
        file_ops.write = write;
        return 0;
    }
    
    void cleanup_module(void)
    {
        remove_proc_entry("printk", NULL);
        printk("exit printk example module\n");
    }
    

    使用示例:

    root@kw:~# insmod printkm.ko
    root@kw:~# echo a string >/proc/printk 
    root@kw:~# dmesg|tail -1
    [193634.164459] a string
    

    【讨论】:

    • 我注意到在 module_init 函数中return -ENOENT 是不明智的,因为这会使insmod 误导性地输出Unknown symbol in module。 insmod 中使用的其他错误或系统调用 init_module() 记录的其他错误也是如此。最好使用不易出错的错误代码,如 EIDRM、EUCLEAN 或 ECANCELED。
    【解决方案2】:

    我认为您可以使用 char 设备。看看Linux Device Driver 3th 第 3 章。使用 *copy_to_user* 和 *copy_from_user* 函数,您可以安全地将数据复制到用户空间或从用户空间复制数据。

    【讨论】:

    • 我认为this 可以提供更多帮助。
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2014-03-07
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2016-03-13
    • 1970-01-01
    相关资源
    最近更新 更多