Chapter 2. Building and Running Modules
It’s high time now to begin programming. This chapter introduces all the essential concepts about modules and kernel programming. In these few pages, we build and run a complete module. Developing such expertise is an essential foundation for any kind of modularized driver. To avoid throwing in too many concepts at once, this chapter talks only about modules, without referring to any specific 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 kernel versions 2.0 through 2.4.[4]
#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 the standard C library function
printf. The kernel needs its own printing
function because it runs by itself, without the help of the C library.
The module can call printk because, after
insmod has loaded it, the module is linked
to the kernel and can access the kernel’s public symbols (functions and
variables, as detailed in the next section). The string
<1> is the priority of the message. We’ve specified a high priority (low cardinal number) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access