Linux 內核用 printk 印出除錯資訊,用法與 C 庫的 printf 類似,只是發生在內核空間。只要在內核程式的任何位置插入 printk,就能把關心的訊息送到螢幕或日誌檔。
printk 會依日誌等級(loglevel)分類訊息。等級以巨集表示,編譯時由預處理器把它和訊息字串拼接在一起,因此等級與格式字串之間不能有逗號。下面兩個例子分別是除錯訊息與臨界訊息:
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)
需要除錯時把 DEBUG 設為 y,不需要時給其他值,然後重新 make 即可。這種做法的好處是除錯輸出可以整批打開或關閉,不必逐處改程式碼。