本文共 3381 字,大约阅读时间需要 11 分钟。
一个内核模块不是一个可以独立执行的文件,而是需要在运行时刻连接入内核的目标文件。所以,它们需要用-c 选项进行编译。而且,所有的内核模块都必须包含特定的标志:
# Makefile for a basic kernel moduleCC=gccMODCFLAGS := -Wall -DMODULE -D__KERNEL__ -DLINUXhello.o: hello.c /usr/include/linux/version.h $(CC) $(MODCFLAGS) -c hello.c echo insmod hello.o to turn it on echo rmmod hello to turn if off echo echo X and kernel programming do not mix. echo Do the insmod and rmmod from outside
所以,并不是剩下的事情就是root(你没有把它编译成root,而是在边缘(注1.1)。对吗?),然后就在你的核心内容里插入或移出hello。当你这样做的时候,要注意到你的新模块在/proc/modules 里。
而且,编译文件不推荐从X 下插入的原因是内核有一条需要用printk 打印的消息,它把它送给了控制台。如果你不使用X,它就送到了你使用的虚拟终端(你用Alt-F<n>选择的哪个)并且你可以看到。相反的,如果你使用了X,就有两种可能性。如果用xterm –C 打开了一个控制台,输出将被送到哪里。如果没有,输出将被送到虚拟终端7——被X“覆盖”的那个。
如果你的内核变得不稳定,你可以在没有X 的情况下得到调试消息。在X 外,printk可以直接从内核中输出到控制台。而如果在X 里,printk 输出到一个用户态的进程(xterm–C)。当进程接收到CPU 时间,它会将其送到X 服务器进程。然后,当X 服务器进程接收到CPU 时间,它将会显示,但是一个不稳定的内核意味着系统将会崩溃或重起,所以你不希望显示错误的消息,然后可能被解释给你什么发生了错误,但是超出了正确的时间。
有些时候在几个源文件之间分出一个内核模块是很有意义的。在这种情况下,你需要做下面的事情:
这里给出一个这样的内核模块的例子。
/* start.c* Copyright (C) 1999 by Ori Pomerantz** "Hello, world" - the kernel module version.* This file includes just the start routine*//* The necessary header files *//* Standard in kernel modules */#include/* We're doing kernel work */#include /* Specifically, a module *//* Deal with CONFIG_MODVERSIONS */#if CONFIG_MODVERSIONS==1#define MODVERSIONS#include #endif/* Initialize the module */int init_module(){ printk("Hello, world - this is the kernel speaking\n"); /* If we return a non zero value, it means that * init_module failed and the kernel module * can't be loaded */ return 0;}
/* stop.c* Copyright (C) 1999 by Ori Pomerantz** "Hello, world" - the kernel module version. This* file includes just the stop routine.*//* The necessary header files *//* Standard in kernel modules */#include/* We're doing kernel work */#define __NO_VERSION__ /* This isn't "the" file of the kernel module *//* Specifically, a module */#include /* Not included by module.h because of the __NO_VERSION__ */#include /* Deal with CONFIG_MODVERSIONS */#if CONFIG_MODVERSIONS==1#define MODVERSIONS#include #endif/* Cleanup - undid whatever init_module did */void cleanup_module(){ printk("Short is the life of a kernel module\n");}
# Makefile for a multifile kernel moduleCC=gccMODCFLAGS := -Wall -DMODULE -D__KERNEL__ -DLINUXhello.o: start.o stop.o ld -m elf_i386 -r -o hello.o start.o stop.ostart.o: start.c /usr/include/linux/version.h $(CC) $(MODCFLAGS) -c start.cstop.o: stop.c /usr/include/linux/version.h $(CC) $(MODCFLAGS) -c stop.c
转载地址:http://wdtaf.baihongyu.com/