【版权声明:转载请保留出处:blog.csdn.net/gentleliu。邮箱:shallnew*163.com】
#include <linux/init.h> //指定初始化和清理函数 #include <linux/module.h> //包含可装载模块需要的大量符号和函数定义 /* * 模块初始化函数,相当于应用程序的main函数,声明为static,因为该函数在其他的方没有意义 */ static int __init hello_init(void) { printk(KERN_ALERT"Hello World enter\n"); return 0; } /* * 清除函数,该函数在模块被移除前注销接口并向系统返回所有资源 */ static void _exit hello_exit(void) { printk(KERN_ALERT"Hello World exit\n"); } module_init(hello_init);//该函数时强制使用的,说明内核初始化函数所在位置,没该定义,,初始化函数永远不会被调用。 module_exit(hello_exit);//该声明对于帮助内核找到模块的清除函数时必需的。如果一个模块未定义清除函数,则内核不允许卸载模块。 MODULE_LICENSE("GPL"); //指定代码所使用的许可证,要求不严格 MODULE_AUTHOR("shallnew*163.com");//描述模块作者下面为一个Makefile:
# CC=$(CROSS_COMPILE)gcc # STRIP=$(CROSS_COMPILE)strip LINUX_SRC = /usr/src/linux-`uname -r` MODULE_NAME = 1_hello SRC_OBJ = hello.o obj-m := $(MODULE_NAME).o $(MODULE_NAME)-objs = $(SRC_OBJ) all: make_module make_module: make -C $(LINUX_SRC) M=`pwd` modules .PHONY: all clean clean: rm -fr *.ko *.o* *.symvers *.markers *.order *.mod* .*cmd .tmp_versions执行:insmod 1_hello.ko
#include <linux/init.h> #include <linux/module.h> #include <asm/current.h> #include <linux/sched.h> static char *whom = "World"; static int times = 1; extern struct task_struct *current; static int __init hello_init(void) { int i; printk(KERN_ALERT"The process is %s, pid:%d\n", current->comm, current->pid); for (i = 0; i < times; i++) { printk(KERN_ALERT"Hello %s\n", whom); } return 0; } static void hello_exit(void) { printk(KERN_ALERT"===%s===\n", __func__); } module_init(hello_init); module_exit(hello_exit); module_param(whom, charp, S_IRUGO); module_param(times, int, S_IRUGO); MODULE_LICENSE("GPL"); MODULE_AUTHOR("shallnew*163.com");