Getting kernel version from linux kernel module at runtime

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 01:16:47

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, then utsname() function from linux/utsname.h is the most standard run-time interface.

The implementation of the virtual /proc/version procfs node uses utsname()->release.

If you want to condition the code based on kernel version in compile time, you can use a preprocessor block such as:

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

It allows you to compare against major/minor versions.

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.

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:

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.

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!