Linux驱动开发:从一个最简单的模块开始

万事总有第一步,对于程序世界,第一步多数都是从Hello World开始,这里也就随大流了:
代码 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, cruel world\n");
}

module_init(hello_init);
module_exit(hello_exit);

Makefile

obj-m += hello.o

KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

all:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules

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

编译:

make

# 大致的输出如下,实际输出和当前使用的环境有关
make -C /lib/modules/6.8.0-100-generic/build M=/home/ps/code/test modules
make[1]: Entering directory '/usr/src/linux-headers-6.8.0-100-generic'
warning: the compiler differs from the one used to build the kernel
  The kernel was built by: x86_64-linux-gnu-gcc-12 (Ubuntu 12.3.0-1ubuntu1~22.04.2) 12.3.0
  You are using:           gcc-12 (Ubuntu 12.3.0-1ubuntu1~22.04.2) 12.3.0
  CC [M]  /home/ps/code/test/hello.o
  MODPOST /home/ps/code/test/Module.symvers
  CC [M]  /home/ps/code/test/hello.mod.o
  LD [M]  /home/ps/code/test/hello.ko
  BTF [M] /home/ps/code/test/hello.ko
Skipping BTF generation for /home/ps/code/test/hello.ko due to unavailability of vmlinux
make[1]: Leaving directory '/usr/src/linux-headers-6.8.0-100-generic'

编译成功后当前文件夹下有hello.ko存在

加载到内核

sudo insmode hello.ko

从内核卸载

sudo rmmod hello

查看系统日志

sudo dmesg |tail

# 大致如下
...
[90123.933097] hello: loading out-of-tree module taints kernel.
[90123.933103] hello: module verification failed: signature and/or required key missing - tainting kernel
[90123.933658] Hello, world
[90178.872518] Goodbye, cruel world

对于日志中上方的两条的警告信息可以不用理会或者自行AI,下方两条就是我们加载和卸载模块时的log,与程序代码预期一致

posted @ 2026-02-03 15:17  bitwoods  阅读(3)  评论(0)    收藏  举报