歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用Linux函數printk打印內核信息的方法

用Linux函數printk打印內核信息的方法

日期:2017/3/1 9:57:39   编辑:Linux編程

Linux內核用函數printk打印調試信息,該函數的用法與C庫打印函數printf格式類似,但在內核使用。用戶可在內核代碼中的某位置加入函數printk,直接把所關心的信息打打印到屏幕上或日志文件中。

函數printk根據日志級別(loglevel)對調試信息進行分類。日志級別用宏定義,展開為一個字符串,在編譯時由預處理器將它和消息文本拼接成一個字符串,因此函數printk中的日志級別和格式字符串間不能有逗號。
下面兩個 printk 的例子,一個是調試信息,一個是臨界信息:

printk(KERN_DEBUG "Here I am: %s:%i\n", _ _FILE_ _, _ _LINE_ _);
printk(KERN_CRIT "I'm trashed; giving up on %p\n", ptr);
樣例:在用戶空間或內核中開啟及關閉打印調試消息 用戶還可以在內核或用戶空間應用程序定義統一的函數打印調試信息,可在Makefile文件中打開或關閉調試函數。定義方法列出如下:

/*debug_on_off.h*/
#undef PDEBUG /* undef it, just in case */
#ifdef SCULL_DEBUG
#ifdef _ _KERNEL_ _
/* This one if debugging is on, and kernel space */
#define PDEBUG(fmt,args...) printk(KERN_DEBUG "scull: " fmt, ## args)
#else
/* This one for user space */
#define PDEBUG(fmt, args...) fprintf(stderr, fmt, ## args)
#endif
#else
#define PDEBUG(fmt, args...) /* not debugging: nothing */
#endif
在文件Makefile加上下面幾行:

# Comment/uncomment the following line to disable/enable debugging
DEBUG = y

# Add your debugging flag (or not) to CFLAGS
ifeq ($(DEBUG),y)
DEBFLAGS = -O -g -DSCULL_DEBUG # "-O"
else
DEBFLAGS = -O2
endif

CFLAGS += $(DEBFLAGS)

更改makefile中的DEBUG值,需要調試信息時,DEBUG = y,不需要時,DEBUG賦其它值。再用make編譯即可。

Copyright © Linux教程網 All Rights Reserved