Chapter 2. Building and Running Modules

It’s high time now to begin programming. This chapter is going to introduce all the essential concepts about modules and kernel programming. In these few pages, we’ll build and run a complete module. Building such expertise is an essential foundation for any kind of modularized driver. To avoid throwing in too many concepts, this chapter only talks about modules, without referring to any device class.

All the kernel items (functions, variables, header files, and macros) that are introduced here are described in a reference section at the end of the chapter.

For the impatient reader, the following code is a complete ``Hello, World'' module (which does nothing in particular). This code will compile and run under Linux 2.0 and later versions, but not under 1.2, as explained later in this chapter.[2]

#define MODULE
#include <linux/module.h>

int init_module(void)      { printk("<1>Hello, world\n"); return 0; }
void cleanup_module(void)  { printk("<1>Goodbye cruel world\n"); }









The printk function is defined in the Linux kernel and behaves similarly to printf; the module can call printk, because after insmod has loaded it, the module is linked to the kernel and can access its symbols. The string <1> is the priority of the message. I’ve specified a high priority in this module because a message with the default priority might not show on the console if you use version 2.0.x of the kernel and an old klogd daemon (you can ignore this issue for now; we’ll ...

Get Linux Device Drivers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.