linux - 内核模块从用户空间获取数据

标签 linux module kernel communication

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

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

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

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

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

最佳答案

...一个简单的模块示例,它只对从用户空间发送的字符串执行 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

关于linux - 内核模块从用户空间获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11794427/

相关文章:

Java 线程创建跟踪

linux - 如何将带有空格的绝对文件路径传递给 linux shell 脚本?

linux - 在 Linux 内核中, header 包含错误

windows - KeEnterGuardedRegion() 与 KeRaiseIrql(APC_LEVEL, &old_irql)

java - Hadoop:mkdir:无法创建/用户

linux - 推荐电子邮件客户端读取/应用 git 补丁?

gradle - 更新 build.gradle 时 IntelliJ 模块设置发生变化

ios - 如何创建 cocoapod 框架并向其中添加文件?

javascript - 在 Node Express 应用程序的模块中使用变量

linux - 将参数从 alsa 应用程序传递到内核驱动程序