在运行时从linux内核模块获取内核版本



我如何获得运行时信息,关于哪个版本的内核是从linux内核模块代码(内核模式)内运行?

按照惯例,Linux内核模块加载机制不允许加载没有针对正在运行的内核编译的模块,因此您所指的"正在运行的内核"很可能在内核模块编译时已经知道了。

对于检索版本字符串常量,旧版本需要包含<linux/version.h>,其他版本需要包含<linux/utsrelease.h>,新版本需要包含<generated/utsrelease.h>。如果您真的想在运行时获得更多的信息,那么linux/utsname.h中的utsname()函数是最标准的运行时接口。

虚拟/proc/version procfs节点的实现使用utsname()->release .

如果您希望在编译时根据内核版本来调整代码,您可以使用预处理器块,如:

#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,16)
...
#else
...
#endif

一次只能安全地为任何一个内核版本构建模块。这意味着在运行时向模块请求是多余的。

你可以在构建时发现这一点,通过查看UTS_RELEASE在最近的内核中的值,这是<generated/utsrelease.h>在其他方式中做到这一点。

为什么我不能为任何版本构建内核模块?

因为内核模块API在设计上是不稳定的,正如内核树在:Documentation/stable_api_nonsense.txt中解释的那样。摘要如下:

Executive Summary
-----------------
You think you want a stable kernel interface, but you really do not, and
you don't even know it.  What you want is a stable running driver, and
you get that only if your driver is in the main kernel tree.  You also
get lots of other good benefits if your driver is in the main kernel
tree, all of which has made Linux into such a strong, stable, and mature
operating system which is the reason you are using it in the first
place.

参见:如何构建一个Linux内核模块,使其与所有内核版本兼容?

如何在编译时做到这一点被问到:是否有一个宏定义来检查Linux内核版本?

最新更新