Kernel 心路历程 模块编写

来源:互联网 发布:linux公社是什么 编辑:程序博客网 时间:2024/05/17 04:30

如果你已经配置好了开发环境,那我们就从内核中最简单的开始. 面对这么多代码,真不知道该从哪学起, 还有我们有万能Google 和 Baidu, 于是乎我们要从写一个helloworld的模块开始.那么就赶紧开始吧.

要写一个helloworld的内部模块主要涉及到2个知识点
Q1: 什么是内核模块

内核模块是Linux内核向外部提供的一个插口,其全称为动态可加载内核模块(Loadable Kernel Module,LKM),我们简称为模块。
这个是概念,那么实际实施起来是什么呢? 说白就是2个函数
module_init();
module_exit();

Q2: 怎么样打印出helloworld?
内核提供了一个类似printf的函数-> printk, 用法和printf 一样.

Makefile

obj-m := helloworld.o#helloworld-objs :=KDIR := /work/code/kos_code/linuxall:    make -C $(KDIR) M=$(PWD) modulesclean:    make -C $(KDIR) M=$(PWD) clean

helloworld.c

#include <linux/init.h>#include <linux/module.h>static bool debug;int __init helloworld_init(void){    if (debug)        printk("%s enable debug mode\n", __func__);    printk("%s %d\n", __func__, __LINE__);    return 0;}void __exit helloworld_exit(void){    printk("%s %d\n", __func__, __LINE__);}module_init(helloworld_init);module_exit(helloworld_exit);MODULE_LICENSE("GPL");MODULE_AUTHOR("Chuck Huang");module_param(debug, bool, 0644);MODULE_PARM_DESC(debug, "Enable debug mode");

运行结果如下图:
这里写图片描述
其中需要注意的是 rmmod的时候是不带dot ko

0 0
原创粉丝点击