如何使用mmap共享用户空间和内核线程
我在寻找一些合适的例子来解决我的问题时遇到了一些困难。我想在用户和内核空间之间共享 4K (4096) 字节的数据。我发现很多想法说我必须从内核分配内存并将其映射到用户空间。有人可以提供一个关于如何在 Linux 2.6.38 中执行此操作的示例吗?有什么好的文档可以解释吗?
提前致谢。
I am having some trouble finding some suitable examples to solve my problem. I want to share 4K (4096) byte of data between user and kernel space. I found many ideas which says I have to allocate memory from kernel and mmap it in user-space. Can someone provide an example on how to do it in Linux 2.6.38. Is there any good document which explains it?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您提出的方法是一种方法,但由于用户空间不在您的控制范围内(意味着任何用户空间程序都有可能侵入内核),因此您为来自用户空间的恶意攻击提供了机会。这种基于内核的内存与用户空间共享也在这里描述:
https://web.archive.org/web/20130217131239/http://www.scs.ch/~frey/linux/memorymap.html
相反,如何在用户空间分配内存,然后从内核使用 API copy_from_user() 和 copy_to_user() 复制到用户空间内存/从用户空间内存复制?如果你想在不同的进程之间共享内存,那么你总是可以使用IPC相关的API来分配和定义内存,例如shmget()等。在这种情况下,内核源代码本身中有很多示例代码。
例如。
fs/checksum.c: 缺失 = __copy_from_user(dst, src, len);
Your proposed way is one way, but as userspace is not within your control (meaning any userspace program have a possibility of poking into the kernel), you are opening up the opportunities for malicious attack from userspace. This kernel-based memory-sharing-with-userspace is also described here:
https://web.archive.org/web/20130217131239/http://www.scs.ch/~frey/linux/memorymap.html
Instead, how about allocating memory in userspace, and then from kernel use the API copy_from_user() and copy_to_user() to copy to/from userspace memory? If u want to share the memory among the different processes, then u can always use IPC related API to allocate and define the memory, eg shmget() etc. And in this case there are lots of sample codes within the kernel source itself.
eg.
fs/checksum.c: missing = __copy_from_user(dst, src, len);