printk列印不能顯示到終端的問題

2021-06-22 17:34:17 字數 2411 閱讀 3699

printk列印不能顯示到終端的問題

2011-05-19 16:01:43

分類: linux

printk

對於做嵌入式或者熟悉linux

核心的人來說,對printk這個函式一定不會感到陌生。printk相當於printf的孿生姐妹,她們乙個執行在使用者態,另乙個則在核心態被人們所熟知。

【原型】

int printk(const char * fmt,…);

【示例】

與大多數展示printf的功能一樣,我們也用乙個helloworld的程式來演示printk的輸出:

編寫乙個核心模組:

#include

#include

#if config_modversions==1

#define modversions

#include

#endif

module_license("gpl");

int init_module()

void cleanup_module()

儲存為檔案hello.c

編寫乙個makefile:

cc=gcc

modcflags:=-o6 -wall -dmodule -d__kernel__ -dlinux

hello.o:hello.c /usr/include/linux/version.h

$(cc) $(modcflags) -c hello.c

echo insmod hello.o to turn it on

儲存為檔案makefile

執行make

我們可以看到生成了乙個hello.o的核心模組,我們想通過這個模組在插入核心的時候輸出

"hello.word-this is the kernel speaking"

這樣一條資訊。

然後我們開始:

[root@localhost root]# insmod hello.o

[root@localhost root]#

並沒有輸出任何訊息。why?

這也是printf和printk的乙個不同的地方

用printk,核心會根據日誌級別,可能把訊息列印到當前控制台上,這個控制台通常是乙個字元模式的終端、乙個串列埠印表機或是乙個並口印表機。這些訊息正常輸出的前提是──日誌輸出級別小於console_loglevel(在核心中數字越小優先順序越高)。

沒有指定日誌級別的printk語句預設採用的級別是 default_ message_loglevel(這個預設級別一般為<4>,即與kern_warning在乙個級別上),其定義在linux26/kernel/printk.c中可以找到

日誌級別一共有8個級別,printk的日誌級別定義如下(在include/linux/kernel.h中):

#define kern_emerg    0

#define kern_alert     1

#define kern_crit       2

#define kern_err        3

#define kern_warning  4

#define kern_notice    5

#define kern_info       6

#define kern_debug     7

現在我們來修改hello.c程式,使printk的輸出級別為最高:

printk("<0>""hello.word-this is the kernel speaking\n");

然後重新編譯hello.o,並插入核心:

[root@localhost root]# insmod hello.o

[root@localhost root]#

message from syslogd@localhost at sat aug 15 05:32:22 2009 ...

localhost kernel: hello.word-this is the kernel speaking

hello,world資訊出現了。

其實printk始終是能輸出資訊的,只不過不一定是到了終端上。我們可以去

/var/log/messages這個檔案裡面去檢視。

如果klogd沒有執行,訊息不會傳遞到使用者空間,只能檢視/proc/kmsg

通過讀寫/proc/sys/kernel/printk檔案可讀取和修改控制台的日誌級別。檢視這個檔案的方法如下:

#cat /proc/sys/kernel/printk 6 4 1 7

上面顯示的4個資料分別對應控制台日誌級別、預設的訊息日誌級別、最低的控制台日誌級別和預設的控制台日誌級別。

可用下面的命令設定當前日誌級別:

# echo 8 > /proc/sys/kernel/printk

這樣所有級別<8,(0-7)的訊息都可以顯示在控制台上. 

Printk在終端顯示

printk 函式為核心空間裡邊的資訊列印函式,就像 c程式設計時用的 printf 函式一樣,專供核心中的資訊展示用,他沒有呼叫 printf 的原因是在編譯核心時還沒有 c的庫函式可以供呼叫。在 linux 中,可以像使用 printf 一樣使用 printk 也可以加上優先順序使用,比如如下 ...

Printk在終端顯示

printk 函式為核心空間裡邊的資訊列印函式,就像 c程式設計時用的 printf 函式一樣,專供核心中的資訊展示用,他沒有呼叫 printf 的原因是在編譯核心時還沒有 c的庫函式可以供呼叫。在 linux 中,可以像使用 printf 一樣使用 printk 也可以加上優先順序使用,比如如下 ...

printk資訊列印到指定檔案 終端 網路

有的時候除錯核心程式,經常要將資訊列印到其他地方如指定檔案或終端還有網路,網路的話dreanice版主寫過個netconsole我這裡就不說了.列印到檔案 include include include include include include include include include ...