如何编写一个简单的 Linux 内核模块

如何编写一个简单的 Linux 内核模块,第1张

编写helloworld.c及其对应的Makefile。

helloworld.c:

#include <linux/module.h>#include <linux/kernel.h>int init_hello_module(void)

{

printk("***************Start***************\n")

printk("Hello World! Start of hello world module!\n") return 0

}void exit_hello_module(void)

{

printk("***************End***************\n")

printk("Hello World! End of hello world module!\n")

}

MODULE_LICENSE("Dual BSD/GPL")

module_init(init_hello_module)

module_exit(exit_hello_module)1234567891011121314151617181920

Makefile:

# To build modules outside of the kernel tree, we run "make"# in the kernel source treethe Makefile these then includes this# Makefile once again.# This conditional selects whether we are being included from the# kernel Makefile or not.# called from kernel build system: just declare what our modules areobj-m := helloworld.oCROSS_COMPILE =

CC= gcc# Assume the source tree is where the running kernel was built

# You should set KERNELDIR in the environment if it's elsewhere

KERNELDIR ?= /usr/src/linux-headers-$(shell uname -r)# The current directory is passed to sub-makes as argument

PWD := $(shell pwd)all: modulesmodules:

$(MAKE) -C $(KERNELDIR) M=$(PWD) modulesclean:

rm -rf *.o *~ core .depend *.symvers .*.cmd *.ko *.mod.c .tmp_versions $(TARGET)

在Makefile中,在obj-m := helloworld.o这句中,.o的文件名要与编译的.c文件名一致。

KERNELDIR ?= /usr/src/linux-headers-$(shell uname -r)指示当前linux系统内核的源码位置。

一、.ko 文件介绍

.ko文件是kernel object文件(内核模块),该文件的意义就是把内核的一些功能移动到内核外边, 需要的时候插入内核,不需要时卸载。

二、优点

(1)这样可以缩小内核体积;

(2)使用方便。

三、.ko文件一般的用处

(1)作为一个功能模块,需要使用时,直接插入运行就行。如在imx6上连接模拟摄像头,先运行模拟摄像头对应的驱动模块 camera.ko文件,然后对应的工程执行文件运行就行。

四、使用.ko 文件

1、加载驱动模块test.ko

(1)方法一 

进入test.ko驱动模块文件所在的目录,然后直接   insmod  test.ko 

(2)方法二 

将test.ko文件拷贝到/lib/module/#uname-r#/目录下,这里,#uname -r#意思是,在终端中输入 

uname -r后显示的内核版本及名称,例如mini2440中#uname-r#就是2.6.32.2-FriendlyARM。

然后 depmod(会在/lib/modules/#uname -r#/目录下生成modules.dep和modules.dep.bb文件,表明模块的依赖关系) 

最后 modprobe test(注意这里无需输入.ko后缀) 即可

注:两种方法的区别

modprobe和insmod类似,都是用来动态加载驱动模块的,区别在于modprobe可以解决load module时的依赖关系,它是通过/lib/modules/#uname -r/modules.dep(.bb)文件来查找依赖关系的;而insmod不能解决依赖问题。也就是说,如果你确定你要加载的驱动模块不依赖其他驱动模块的话,既可以insmod也可以modprobe,当然insmod可以在任何目录下执行,更方便一些。而如果你要加载的驱动模块还依赖其他ko驱动模块的话,就只能将模块拷贝到上述的特定目录,depmod后再modprobe。

我感觉首先应该明确需求,

如果是实现连接池功能,是不用做查询,插入等 *** 作的。

只需要提供接口,给调用程序返回connection,并且把用完的

connection再回收,以供下次调用。所以,概括说就是一次建立大量连

接(比如500个),并且管理这些连接,使它们能反复使用,这样就避

免了不断新建和销毁connection浪费时间。

关于实现:连接池的算法是通用的,这个可以C语音实现。但是具体的

取得数据库连接(get

connection),需要不同的数据库驱动,这个不

可能实现通用。

lz现在做的怎么样了?给个参考,mod_mysql_pool

是一个mySQl的连接池。

--有道启新嵌入式培训


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/6240204.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-18
下一篇 2023-03-18

发表评论

登录后才能评论

评论列表(0条)

保存