Anu*_*kar 8 linux linux-device-driver linux-kernel
在linux设备驱动程序开发中,file_operations结构使用"struct module*owner".
THIS_MODULE?最小可运行示例
每当您创建内核模块时,内核的构建机制都会struct module为您生成一个对象,并指向THIS_MODULE它。
该结构体包含许多字段,其中一些字段可以使用模块宏进行设置,例如MODULE_VERSION.
此示例展示了如何访问该信息module_info.c::
#include <linux/module.h>
#include <linux/kernel.h>
static int myinit(void)
{
    /* Set by default based on the module file name. */
    pr_info("name    = %s\n", THIS_MODULE->name);
    pr_info("version = %s\n", THIS_MODULE->version);
    return 0;
}
static void myexit(void) {}
module_init(myinit)
module_exit(myexit)
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL");
Dmesg 输出:
name    = module_info
version = 1.0
某些MODULE_INFO字段还可以通过以下方式“访问”:
cat /sys/module/module_info/versionmodinfo /module_info.ko | grep -E '^version:'由于该对象的地址struct module在所有模块中必须是唯一的,因此它可以作为一个很好的论据,fops.owner如下所述: https: //stackoverflow.com/a/19468893/895245。这是该用法的一个最小示例。
使用此 QEMU + Buildroot 设置在 Linux 内核 4.16 中进行了测试。
小智 1
file_operation是用于连接驱动程序的设备号和文件操作的主要结构之一。
struct module *owner根本不是函数指针,而是指向<linux/module.h>.THIS_MODULE,它拥有该模块的所有权。struct module *owner是THIS_MODULE为了防止模块在使用时被卸载。