如何写入/ proc内核模块

时间:2015-03-09 19:43:10

标签: 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

1 个答案:

答案 0 :(得分:1)

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

$ ls -l /proc | grep w

例如sysrq-trigger

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

然后在内核源代码中找到相应的字符串:

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

这给了你:

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

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

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中的内置代码索引器)。

相关问题