简体   繁体   English

以编程方式检查运行时是否存在Linux内核模块

[英]Programmatically check whether a linux kernel module exists or not at runtime

I am writing a C daemon, which depends on the existence of two kernel modules in order to do its job. 我正在编写一个C守护进程,它依赖于两个内核模块的存在才能完成它的工作。 The program does not directly use these (or any other) modules. 该程序不直接使用这些(或任何其他)模块。 It only needs them to exist. 它只需要它们存在。 Therefore, I would like to programmatically check whether these modules are already loaded or not, in order to warn the user at runtime. 因此,我想以编程方式检查这些模块是否已加载,以便在运行时警告用户。

Before I start to do things like parsing /proc/modules or lsmod output, does a utility function already exist somewhere? 在我开始执行诸如解析/proc/moduleslsmod输出之类的操作之前,某个实用程序函数是否已经存在? Something like is_module_loaded(const char* name) ; 类似于is_module_loaded(const char* name) ;

I am pretty sure this has been asked before. 我很确定以前曾经问过这个问题。 However, I think I am missing the correct terms to search for this. 但是,我想我错过了正确的搜索条件。

There is no such function. 没有这样的功能。 In fact, the source code of lsmod ( lsmod.c ) has the following line in it which should lead you to your solution: 事实上,lsmod( lsmod.c )的源代码中包含以下行,它可以引导您找到解决方案:

file = fopen("/proc/modules", "r");

There is also a deprecated query_module but it appears to only exist in kernel headers these days. 还有一个不推荐使用的query_module但它现在似乎只存在于内核头文件中。

You can use popen and lsmod | grep 你可以使用popenlsmod | grep lsmod | grep trick: lsmod | grep技巧:

  FILE *fd = popen("lsmod | grep module_name", "r");

  char buf[16];
  if (fread (buf, 1, sizeof (buf), fd) > 0) // if there is some result the module must be loaded
    printf ("module is loaded\n");
  else
    printf ("module is not loaded\n");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM