Next: Kernel Modules Versus Applications
Up: Device Drivers
Previous: Building and Running Modules
The following code is a complete "hello world" module:
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void)
{
printk(KERN_ALERT "Hello, world\n");
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT "Goodbye, cruel world\n");
}
module_init(hello_init);
module_exit(hello_exit);
- This module defines two functions,
- one to be invoked when the module is loaded into the kernel ()
- and one for when the module is removed ().
- The and lines use special kernel macros to indicate the role of these two functions. Another special macro
(
) is used to tell the kernel that this module bears a free license; without such a declaration, the kernel complains when the module is loaded.
- The function is defined in the Linux kernel and made available to modules; it behaves similarly to the standard C library function . The kernel needs its own printing function because it runs by itself, without the help of the C library.
- The module can call because, after has loaded it, the module is linked to the kernel and can access the kernel's public symbols (functions and variables).
- The string is the priority of the message. We've specified a high priority in this module, because a message with the default priority might not show up anywhere useful, depending on the kernel version you are running, the version of the daemon, and your configuration.
- You can test the module with the and utilities, as shown below. Note that only the superuser can load and unload a module.
[root@ozdogan week7]# make
make -C /lib/modules/2.6.19.2/build M=/home/ozdogan/week7 modules
make[1]: Entering directory `/usr/src/kernels/linux-2.6.19.2'
CC [M] /home/ozdogan/week7/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/ozdogan/week7/hello.mod.o
LD [M] /home/ozdogan/week7/hello.ko
make[1]: Leaving directory `/usr/src/kernels/linux-2.6.19.2'
% su
root# insmod ./hello.ko
Hello, world
root# rmmod hello
Goodbye cruel world
root#
- For the above sequence of commands to work, you must have a properly configured and built kernel tree in a place where the makefile is able to find it (/usr/src/linux-2.6.10 in the example shown). According to the mechanism your system uses to deliver the message lines, your output may be different. In particular, the previous screen dump was taken from a text console; if you are running and from a terminal emulator running under the window system, you won't see anything on your screen. The message goes to one of the system log files, such as /var/log/messages (the name of the actual file varies between Linux distributions).
Next: Kernel Modules Versus Applications
Up: Device Drivers
Previous: Building and Running Modules
Cem Ozdogan
2007-04-16