简体   繁体   English

如何写到/ proc内核模块

[英]How to write to a /proc kernel module

How can I get data when a user writes to proc? 用户写入proc时如何获取数据? (Ie: echo "foo" > /proc/myproc) (即:echo“ foo”> / proc / myproc)

I've seen reading from proc (ie user does a "cat /proc/myproc") as detailed from this site: http://www.linux.com/learn/linux-training/39972-kernel-debugging-with-proc-qsequenceq-files-part-2-of-3 我已经看到了从proc读取的内容(例如,用户执行的是“ cat / proc / myproc”),该网站对此进行了详细说明: http : //www.linux.com/learn/linux-training/39972-kernel-debugging-with- PROC-qsequenceq-文件部分-2-的-3

That seems to work well enough, but I haven't seen the analogous method for writing. 这似乎已经足够好了,但是我还没有看到类似的编写方法。 Also, I have checked out TLDP, but their article seems way out of date: http://tldp.org/LDP/lkmpg/2.6/html/x769.html 另外,我已经签出了TLDP,但是他们的文章似乎过时了: http ://tldp.org/LDP/lkmpg/2.6/html/x769.html

Actually the kernel API for dealing with /proc and /sys may vary between different kernel versions. 实际上,在不同的内核版本之间,用于处理/proc/sys的内核API可能会有所不同。 Good news is that kernel itself is quite self explanatory. 好消息是内核本身很容易说明。 Means you can easily find an example of code just exploring sources. 意味着您只需探索源代码就可以轻松找到代码示例。 Just look for some file in /proc which supports write operation: 只需在/proc查找一些支持写操作的文件:

$ ls -l /proc | grep w

For example sysrq-trigger does: 例如, sysrq-trigger执行以下操作:

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

Then find the corresponding string in kernel sources: 然后在内核源代码中找到相应的字符串:

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

Which gives you: 这给你:

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

Now look into code in found file (look here for version 3.18): 现在查看找到的文件中的代码( 在此处查看版本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");
}

The same you can do for some sysfs file. 您可以对某些sysfs文件执行相同的操作。 For faster search use some code indexer (like cscope for vim, or built-in code indexer in Eclipse). 为了加快搜索速度,请使用一些代码索引器(例如cscope for vim,或Eclipse中的内置代码索引器)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM