第一个内核模块hello world"/>
第一个内核模块hello world
1、源码树的下载和编译(只是研究内核模块的话,应该不需要源码树的)
下载很简单,压缩包解压
编译:make menuconfig
make bzImage -j4
参考
2、
cd /usr/src/linux-4.12.10/drivers/char
建立demo目录,用来存放自己的内核模块
demo目录下新建hello.c 和 Makefile文件
//hello.c #include <linux/init.h> #include <linux/module.h>MODULE_LICENSE("Dual BSD/GPL");static int hello_init(void) {printk(KERN_ALERT "hello world!\n");return 0; }static void hello_exit(void) {printk(KERN_ALERT "goodbye!\n"); }module_init(hello_init); module_exit(hello_exit);//Makefile ifeq ($(KERNELRELEASE),) KERNELDIR ?= /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) modules:$(MAKE) -C $(KERNELDIR) M=$(PWD) modules modules_install:$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install clean:rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions Module* modules* .PHONY: modules modules_install clean else obj-m := hello.o endif
参考
编译结果:
ninjame@ubuntu1604:/usr/src/linux-4.12.10/drivers/char/demo$ sudo make make -C /lib/modules/4.4.80-040480-generic/build M=/usr/src/linux-4.12.10/drivers/char/demo modules make[1]: Entering directory '/usr/src/linux-headers-4.4.80-040480-generic'CC [M] /usr/src/linux-4.12.10/drivers/char/demo/hello.oBuilding modules, stage 2.MODPOST 1 modulesCC /usr/src/linux-4.12.10/drivers/char/demo/hello.mod.oLD [M] /usr/src/linux-4.12.10/drivers/char/demo/hello.ko make[1]: Leaving directory '/usr/src/linux-headers-4.4.80-040480-generic'
模块加载和效果
ninjame@ubuntu1604:/usr/src/linux-4.12.10/drivers/char/demo$ sudo insmod hello.ko ninjame@ubuntu1604:/usr/src/linux-4.12.10/drivers/char/demo$ dmesg | tail [ 15.300169] r8169 0000:01:00.0 enp1s0: link down [ 15.300185] r8169 0000:01:00.0 enp1s0: link down [ 15.300230] IPv6: ADDRCONF(NETDEV_UP): enp1s0: link is not ready [ 16.840866] r8169 0000:01:00.0 enp1s0: link up [ 16.840873] IPv6: ADDRCONF(NETDEV_CHANGE): enp1s0: link becomes ready [ 18.016626] Bluetooth: BNEP (Ethernet Emulation) ver 1.3 [ 18.016628] Bluetooth: BNEP filters: protocol multicast [ 18.016631] Bluetooth: BNEP socket layer initialized [12219.748060] hello: module verification failed: signature and/or required key missing - tainting kernel [12219.748268] hello world!
转载于:.html
更多推荐
第一个内核模块hello world
发布评论