From: http://hi.baidu.com/zkheartboy/blog/item/18d4fdc48b0249aa8326ac7c.html
I saw several posts asking about Linux kernel programming yesterday. Many of them are stuck in the entry-level questions. I will sort out the preliminary process of getting started. For Linux 2.6 kernel, you need to install the kernel-devel package on your machine, which is required by the compiling module: the kernel header file and some makefiles.
1. Hello World Program:
Code:/* file: Hello. C */
# Ifndef _ KERNEL __
# DEFINE _ KERNEL __
# Endif
# Ifndef Module
# Define Module
# Endif
# Include <Linux/init. h>;
# Include <Linux/module. h>;
# Include <Linux/kernel. h>;
Static int hello_init (void)
{
Printk (kern_alert "hello, the fucking crazy world/N ");
Return 0;
}
Static void hello_exit (void)
{
Printk (kern_alert "bye, the fucking crazy world! /N ");
}
Module_init (hello_init );
Module_exit (hello_exit );
Module_license ("GPL ");
Module_author ("albcamus <albcamus@163.com> ;");
The kbuild subsystem of the 2.6 kernel has an essential change compared with the 2.4 kernel. Let's try to compile this program in two ways:
1. You can write a makefile in this directory.
Code: obj-M: = Hell. o
Clean:
Rm-RF *. O. *. CMD *. Ko *. Mod. C. tmp_versions
Then compile with the following command line:
Make-C/lib/modules/'uname-R'/build M = 'pwd' modules
At this moment, we can see that many files are generated. Hello. Ko is the kernel module we need.
2. Be professional and write makefile as follows:
Code: obj-M: = Hello. o
Kernelbuild: =/lib/modules/'uname-R'/build
Default:
Make-C $ (kernelbuild) M = $ (shell PWD) Modules
Clean:
Rm-RF *. O. *. CMD *. Ko *. Mod. C. tmp_versions
Then you just need to make it.
Use the insmod command to insert the module:
Insmod./Hello. Ko
At this time, you may ask: why is no output displayed on my screen? This is the log record level of the console and the level specified during your printk message (in this example
Kern_alert, which is the second highest level after kern_emerg. In any case, you can tail
Or cat looks at the last few lines of the system log. The system log is usually/var/log/messages, or you can directly use the dmesg command to see the output.
Ii. header file problems.
C programmers know that to use an external function, they should # include a header file, which contains the prototype of the function ). The header file of the kernel is
Include/, where include/ASM is a symbolic link pointing to the specific architecture directory of your kernel. For example, if my system is i386, then
Include/ASM points to include/asm-i386.
In kernel programming, we cannot connect to the libc library or use functions in the libc library.
Trouble. Some important functions, such as strcpy, strcmp, and snprintf, kernel also implements and exports (export) for us, and we need
# Include-related header files. In include/Linux and include/ASM, you need to find the header file in which the function you want to declare and
# Include.