在运行时从 Linux 内核模块获取内核版本
如何从 Linux 内核模块代码(内核模式)中获取有关正在运行的内核版本的运行时信息?
how can I obtain runtime information about which version of kernel is running from inside linux kernel module code (kernel mode)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
按照惯例,Linux 内核模块加载机制不允许加载未针对正在运行的内核编译的模块,因此您所指的“正在运行的内核”很可能在内核模块编译时已经知道。
为了检索版本字符串常量,旧版本要求您包含
,其他版本要求
,较新版本则 <代码><生成/utsrelease.h>。如果您确实想在运行时获取更多信息,那么linux/utsname.h
中的utsname()
函数是最标准的运行时接口。虚拟
/proc/version
procfs节点的实现使用utsname()->release
。如果您想在编译时根据内核版本调整代码,您可以使用预处理器块,例如:
它允许您与主要/次要版本进行比较。
By convention, Linux kernel module loading mechanism doesn't allow loading modules that were not compiled against the running kernel, so the "running kernel" you are referring to is most likely is already known at kernel module compilation time.
For retrieving the version string constant, older versions require you to include
<linux/version.h>
, others<linux/utsrelease.h>
, and newer ones<generated/utsrelease.h>
. If you really want to get more information at run-time, thenutsname()
function fromlinux/utsname.h
is the most standard run-time interface.The implementation of the virtual
/proc/version
procfs node usesutsname()->release
.If you want to condition the code based on kernel version in compile time, you can use a preprocessor block such as:
It allows you to compare against major/minor versions.
您一次只能安全地为任何一个内核版本构建模块。这意味着在运行时向模块请求是多余的。
您可以在构建时通过查看最近内核中
UTS_RELEASE
的值来找到这一点,该值位于
以及其他执行此操作的方法中。You can only safely build a module for any one kernel version at a time. This means that asking from a module at runtime is redundant.
You can find this out at build time, by looking at the value of
UTS_RELEASE
in recent kernels this is in<generated/utsrelease.h>
amongst other ways of doing this.为什么我不能为任何版本构建内核模块?
因为内核模块 API 在设计上不稳定,如内核树中所述:
Documentation/stable_api_nonsense.txt
。摘要如下:另请参阅:如何构建Linux 内核模块,以便它与所有内核版本兼容?
在编译时询问如何做到这一点:是否有宏定义来检查Linux内核版本?
Why can't I build a kernel module for any version?
Because the kernel module API is unstable by design as explained in the kernel tree at:
Documentation/stable_api_nonsense.txt
. The summary reads:See also: How to build a Linux kernel module so that it is compatible with all kernel releases?
How to do it at compile time was asked at: Is there a macro definition to check the Linux kernel version?