【问题标题】:Getting kernel version from linux kernel module at runtime在运行时从 linux 内核模块获取内核版本
【发布时间】:2014-09-03 19:18:49
【问题描述】:

如何从 linux 内核模块代码(内核模式)中获取有关正在运行的内核版本的运行时信息?

【问题讨论】:

    标签: linux-kernel kernel-module kernel-mode


    【解决方案1】:

    按照惯例,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
    

    它允许您与主要/次要版本进行比较。

    【讨论】:

      【解决方案2】:

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

      您可以在构建时发现这一点,通过查看最近内核中UTS_RELEASE 的值,这是在&lt;generated/utsrelease.h&gt; 中以及其他执行此操作的方法。

      【讨论】:

        【解决方案3】:

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

        因为内核模块 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.
        

        另见:How to build a Linux kernel module so that it is compatible with all kernel releases?

        在编译时如何做被问到:Is there a macro definition to check the Linux kernel version?

        【讨论】:

          猜你喜欢
          • 2018-11-27
          • 1970-01-01
          • 2016-01-16
          • 2023-03-27
          • 2021-06-10
          • 2012-04-11
          • 2013-12-17
          • 1970-01-01
          相关资源
          最近更新 更多