Why writing files from the kernel is bad ?
https://kernelnewbies.org/FAQ/WhyWritingFilesFromKernelIsBad
Reasons
The question "how to I open/read/write files from the kernel ?" is often asked on the kernelnewbies mailing list. However, the question cannot really be answered: opening, reading and writing files from within the kernel is usually a bad idea. Generally speaking, trying to use any of the sys_*() functions from the kernel itself is a bad idea.
For several reasons:
-
Selecting where and in what format to read/write data is a policy and policy does not belong to kernel. A userland daemon is much easier to replace with one that receives or sends the data over a network, generates or converts them from/to different format etc.
-
Filesystem operations need a user context (i.e.: current != NULL). You can't be sure you're in user context so you can't write something from (for example) an interrupt handler.
-
The kernel allows multiple filesystem namespaces for user processes. Which one should it use? How do you make sure it indeed uses the one you want?
-
Kernel should not depend on particular layout of a filesystem nor on availability of writable filesystem. The location of the file is a policy decision and policy decisions should be done in userspace. Maybe you want to dump the kernel output in a remote MySQL server tomorrow, that kind of policy is so much easier in userland.
-
Kernel code should be kept simple and stupid, because any bug in it is likely to have serious consequences. Working with files requires being aware of various locking issues and would add unnecessary complexity.
The good ways to exchange data with user space
There are several ways to exchange informations between userspace and the kernel, and the one to use really depends on what you want to do:
-
kernel module parameters are useful to set general configuration options for your modules
-
device firmware should be loaded through the request_firmware() API
-
sysfs is useful to get/set attributes to devices
-
netlink sockets
Using /proc is not anymore a good idea these days, except if you want to export information related to processes.
The good way to create device nodes
The good way is to have your device exported in sysfs and to let udev create the device node in /dev. Do not call try to call sys_mknod() from the kernel.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通