简体   繁体   English

Linux内核-读/写到文件

[英]Linux Kernel - Read/Write to a File

I'm working on a LKM which needs to retrieve and write a certain set of information to files. 我正在研究一个LKM,该LKM需要检索并将某些信息写入文件。 I looked up common ways to do so, but could not find a working one for Linux 4.x. 我查找了执行此操作的常用方法,但是找不到适用于Linux 4.x的方法。 I also found out that it is possible to retrieve system calls from memory and effectively call them. 我还发现,可以从内存中检索系统调用并有效地调用它们。

As I found currently no better way I'd be interested if it'd be feasible to find the system call table, and call open , read/write and close this way. 如我目前所发现的,没有更好的方法了,如果能找到系统调用表并以这种方式调用openread / writeclose ,我会很感兴趣。

This is strongly discouraged in most situations. 在大多数情况下,强烈建议不要这样做。

https://www.linuxjournal.com/article/8110 was a really good read for me the first time I thought I had to do this as well. https://www.linuxjournal.com/article/8110对我来说真的是一本好书,我以为我也必须这样做。

From within the Linux kernel, however, reading data out of a file for configuration information is considered to be forbidden. 但是,从Linux内核内部,禁止从文件中读取数据以获取配置信息。 This is due to a vast array of different problems that could result if a developer tries to do this. 这是由于开发人员尝试执行此操作可能会导致各种各样的问题。

Indeed this is possible to do using system calls from within the kernel, but the practice of calling system calls from within the kernel is also generally discouraged. 确实,使用内核内部的系统调用可以做到这一点,但是通常也不建议从内核内部调用系统调用。 They're designed as interfaces for userspace applications to ask things of the kernel, not for the kernel to get itself to do work. 它们被设计为用户空间应用程序询问内核的接口,而不是让内核自行工作的接口。

What kind of files do you want to manipulate from within the kernel? 您要在内核中处理哪种文件? If the kind of file you'd like to manipulate is provided by the proc filesystem or the sysfs filesystem or the dev filesystem, you can modify the contents of the file from within the kernel (since the kernel provides these to userspace itself) -- this should be done NOT with file manipulation calls. 如果您要操作的文件类型是proc文件系统,sysfs文件系统或dev文件系统提供的,则可以在内核中修改文件的内容(因为内核将这些内容提供给用户空间本身)-不应使用文件操作调用来完成此操作。 If it's a normal userspace file, almost never do you want the kernel to be able to modify it. 如果它是普通的用户空间文件,则几乎永远不会希望内核能够对其进行修改。

If you provide more specifics I'd be interested to hear them, but this is usually a bad idea. 如果您提供更多细节,我很想听听他们,但这通常是个坏主意。

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

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