printk无法打印信息

来源:互联网 发布:mysql实时同步工具 编辑:程序博客网 时间:2024/06/11 21:49

转自http://blog.chinaunix.net/uid-25811099-id-326899.html

 

对于做嵌入式或者熟悉linux内核的人来说,对printk这个函数一定不会感到陌生。printk相当于printf的孪生姐妹,她们一个运行在用户态,另一个则在内核态被人们所熟知。

  【原型】

  int printk(const char * fmt,…);

  【示例】

  与大多数展示printf的功能一样,我们也用一个helloworld的程序来演示printk的输出:

  编写一个内核模块:

  #include<linux/kernel.h>

  #include<linux/module.h>

  #if CONFIG_MODVERSIONS==1

  #define MODVERSIONS

  #include<linux/modversions.h>

  #endif

  MODULE_LICENSE("GPL");

  int init_module()

  {

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

  return 0;

  }

  void cleanup_module()

  {

  printk("Short is the life of a kernel module\n");

  }

  保存为文件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)的消息都可以显示在控制台上. 

 

原创粉丝点击