linux内核编程之hello,world

来源:互联网 发布:js escape替代方法 编辑:程序博客网 时间:2024/06/05 01:07

【版权声明:转载请保留出处: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)stripLINUX_SRC = /usr/src/linux-`uname -r`MODULE_NAME = 1_helloSRC_OBJ = hello.oobj-m := $(MODULE_NAME).o$(MODULE_NAME)-objs = $(SRC_OBJ)all: make_modulemake_module:make -C $(LINUX_SRC) M=`pwd` modules.PHONY: all cleanclean:rm -fr *.ko *.o* *.symvers *.markers *.order *.mod* .*cmd .tmp_versions
执行:insmod 1_hello.ko
使用查看输出信息:dmesg | tail
插入模块是可以带参数,下面给一个可以带参数的hello,world:

#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");

运行:insmod 1_hello.ko whom=shalnew times=10

2 0