Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 内核模块编程:printk() 内核日志输出与模块加载卸载实战

編輯:關於 Linux

printk() 是内核空间的日志输出函数,类似用户空间的 printf(),输出至内核环形缓冲区,可通过 dmesg 或 /var/log/kern.log 查看。本文通过最简 Hello World 模块演示编写、编译、加载、查看日志、卸载全流程。

一、编写内核模块 hello.c

#include 
#include 

int init_module(void) {
    printk(KERN_INFO "Welcome...\n");
    return 0;
}

void cleanup_module(void) {
    printk(KERN_INFO "Bye...\n");
}

二、编写 Makefile

obj-m := hello.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules

clean:
    rm -f *.o *.ko *.mod.c Module.symvers modules.order

三、编译生成 .ko 模块

make
# 生成 hello.ko

四、加载模块并查看 printk 输出

sudo insmod hello.ko
lsmod | grep hello
dmesg | tail
# 应显示:Welcome...

# 查看系统日志
cat /var/log/syslog | grep Welcome
# 或
cat /var/log/kern.log

五、卸载模块

sudo rmmod hello
dmesg | tail
# 应显示:Bye...

六、printk 日志级别常量

宏级别用途
KERN_EMERG0系统不可用
KERN_ALERT1需立即处理
KERN_CRIT2严重错误
KERN_ERR3错误
KERN_WARNING4警告
KERN_NOTICE5正常但重要
KERN_INFO6信息
KERN_DEBUG7调试

默认控制台显示级别由 console_loglevel 控制(通常 7),dmesg -n 可调整。

内核模块 printk 输出示意图

掌握 printk 与模块编译加载流程,是 Linux 内核开发入门的第一步。进阶可学习 procfs/sysfs 接口、字符/块设备驱动、中断处理与并发控制。

Copyright © Windows教程網 All Rights Reserved