Lavair
Lavair

Reputation: 946

What is a module in C?

A similar question appeared already one time for C++ but the answers and the question itself weren't really satisfying.
I've read a .c File (github link), which included the <linux/module.h> and passed its static functions to module_init(foo) and module_exit(foo). So what is the general purpose of a module, of the <linux/module.h> file in this context, and of especially those two methods?

Upvotes: 5

Views: 4864

Answers (2)

ShivYaragatti
ShivYaragatti

Reputation: 398

This is specific to Linux operating system kernel (module) programming and it not general C/C++ programming as such, we can say this is kindof or similar to some framework to develop Linux kernel programs.

Linux operating system kernel supports dynamically adding or removing piece of program into/from the kernel. these API are used to write such kernel programs(popularly known as modules).

so module_init() is called when you try to insert module to kernel and model_exit() is called to cleanup things when we remove module after doing its job.

following is simplest kernel module you can try

#include "linux/init.h" /*(use angle brackets here if it doesn't work)*/
#include "linux/module.h"

MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void){
   printk(KERN_ALERT "Hello good try keep it up\n");
   return 0;
}

static void hello_exit(void){
     printk(KERN_ALERT "Goodbye .. take care\n");
}

module_init(hello_init);
module_exit(hello_exit); 

Upvotes: 3

gsamaras
gsamaras

Reputation: 73366

It is for the Linux Kernel Module. Section 1.1 mentions:

So, you want to write a kernel module. [..] now you want to get to where the real action is, What exactly is a kernel module? Modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel [..]. For example, one type of module is the device driver, which allows the kernel to access hardware connected to the system.

Then, in section 2.3:

The macros module_init() and module_exit() macros initialize and cleanup your functions.

Example:

module_init(hello_2_init);
module_exit(hello_2_exit);

where both this dymmy functions call printk(); saying hello/goodbye world.

In section 3.1.1:

A module always begins with either the init_module() or the function you specify with module_init() call. This is the entry function for modules; it tells the kernel what functionality the module provides and sets up the kernel to run the module's functions when they're needed.

All modules end by calling either cleanup_module() or the function you specify with the module_exit() call. This is the exit function for modules; it undoes whatever entry function did. It unregisters the functionality that the entry function registered.

Upvotes: 5

Related Questions