linux内核编程之hello,world

【版权声明:转载请保留出处: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
使用查看输出信息: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值