11

I am writing a C daemon, which depends on the existence of two kernel modules in order to do its job. 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? Something like 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.

Sam
  • 7,252
  • 16
  • 46
  • 65

2 Answers2

18

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:

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

There is also a deprecated query_module but it appears to only exist in kernel headers these days.

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
  • My question was ambiguous enough to both ask for the existence of such function and how to code the functionality. Therefore, I am going to upvote your answer and accept @tozka answer, because it works for me. Thanks for the explanations! –  Oct 20 '12 at 16:06
  • I used this solution. I hope the text format stays put for many years. I'm checking for "Live" in field 5: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/s2-proc-modules – JCCyC Jan 21 '21 at 19:15
5

You can use popen and lsmod | grep trick:

  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");
tozka
  • 3,211
  • 19
  • 23
  • Looks very dirty but it works and I have never thought about such simple solution. Cheers –  Oct 20 '12 at 16:07
  • 1
    Given that lsmod opens "/proc/modules", and that grep involves another process and additional file opens for the pipe, would it be more efficient to use "grep module_name /proc/modules" and check whether there is any output from that instead? This would also work even if lsmod wasn't available. – Jeremy Jul 12 '16 at 22:17
  • 1
    A better grep would be '^module_name ' with a space after the name. – JCCyC Jan 21 '21 at 19:17