c - 如何写入/proc 内核模块

标签 c linux-kernel kernel

当用户写入proc时,如何获取数据? (即:echo "foo">/proc/myproc)

我看过从 proc 读取的内容(即用户执行“cat/proc/myproc”),详细信息来自此站点:http://www.linux.com/learn/linux-training/39972-kernel-debugging-with-proc-qsequenceq-files-part-2-of-3

这似乎工作得很好,但我还没有看到类似的写作方法。另外,我查看了 TLDP,但他们的文章似乎已经过时了:http://tldp.org/LDP/lkmpg/2.6/html/x769.html

最佳答案

实际上,用于处理/proc/sys 的内核API 可能因内核版本而异。好消息是内核本身是不言自明的。意味着您可以轻松找到代码示例,只需探索源代码即可。只需在 /proc 中寻找一些支持写操作的文件:

$ ls -l /proc | grep w

例如 sysrq-trigger 做:

--w-------  1 root root  0 Mar 12 00:41 sysrq-trigger

然后在kernel sources中找到对应的字符串:

$ find . -name '*.[ch]' -exec grep -Hn '"sysrq-trigger"' {} \;

这给了你:

drivers/tty/sysrq.c:1105:   if (!proc_create("sysrq-trigger", S_IWUSR, NULL,

现在查看找到的文件中的代码(查看 here 版本 3.18):

static ssize_t write_sysrq_trigger(struct file *file, const char __user *buf,
                                   size_t count, loff_t *ppos)
{
        if (count) {
                char c;

                if (get_user(c, buf))
                        return -EFAULT;
                __handle_sysrq(c, false);
        }

        return count;
}

static const struct file_operations proc_sysrq_trigger_operations = {
        .write          = write_sysrq_trigger,
        .llseek         = noop_llseek,
};

static void sysrq_init_procfs(void)
{
        if (!proc_create("sysrq-trigger", S_IWUSR, NULL,
                         &proc_sysrq_trigger_operations))
                pr_err("Failed to register proc interface\n");
}

您可以对某些 sysfs 文件执行相同的操作。为了更快地搜索,使用一些代码索引器(例如用于 vim 的 cscope,或 Eclipse 中的内置代码索引器)。

关于c - 如何写入/proc 内核模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28950478/

相关文章:

linux - 如何在 Makefile 中查看内核版本

c - 根据用户输入求解表达式

android - c undefined reference to function - 编译android/linux内核

linux - linux内核如何知道在系统调用中作为参数传递的地址无效?

linux - 如何使kill命令更快

ubuntu - 更新ubuntu内核的问题

编译 tpm 驱动程序给出 tpm_open() undefined

c - 从 C 中的日期中提取数字

C - *x++ = *y++ 是否定义明确?

linux - 在 minicom 中打印额外的空格