Hello, World 模块的 printk()

来源:互联网 发布:网吧身份证登记软件 编辑:程序博客网 时间:2024/05/22 12:19

学习LDD3的时候,首先是编写Hello,World

    printk(KERN_ALERT "Hello world\n");

编译成功后运行,发现打印信息不知道输出到哪里了?

我的系统是 VirtualBox + Ubuntu8.10

然后,Google了一下,得到下面的信息

(1)如果系统同时运行了klogd和syslogd,则无论console_loglevel为何值,都将内核消息追加到/var/log/message中(否则处理方式就取决于对syslogd的设置)
(2)如果klogd没有运行,这些消息就不会被传递到用户空间,除非你读取/proc/kmsg 或者 用 dmesg 命令
但是,我发现上面两个地方都没有打印输出。


显然,我的系统中klogd和syslogd都是运行的,
$ ps aux | grep -E 'syslogd|klogd'
syslog 4371 0.0 0.0 2012 736 ? Ss 17:23 0:00 /sbin/syslogd -u syslog
root 4416 0.0 0.0 1940 540 ? S 17:23 0:02 /bin/dd bs 1 if /proc/kmsg of /var/run/klogd/kmsg
klog 4418 0.0 0.2 3512 2292 ? Ss 17:23 0:01 /sbin/klogd -P /var/run/klogd/kmsg
1000 7924 0.0 0.0 3240 860 pts/2 S+ 21:00 0:00 grep -E syslogd|klogd


通过搜索Ubuntu论坛,有人提到了日志文件/var/log/syslog。
我发现,Hello Workd 的打印信息确实是在这里。我很奇怪,为什么会是在这里呢?
那么,我们需要查看syslogd的配置文件 /etc/syslog.conf & “man syslog.conf"

$ vim /etc/syslog.conf
...
auth,authpriv.*         /var/log/auth.log
*.*;auth,authpriv.none      -/var/log/syslog
...

$ man syslog.conf
...
Multiple  facilities may be specified for a single priority pattern in one statement using the comma (‘‘,’’) opera‐
tor to separate the facilities.  You may specify as many facilities as you want.  Remember that only  the  facility
part from such a statement is taken, a priority part would be skipped.  For example, it means that instead of writ‐
ing "kern.info,auth.info" you just write "kern,auth.info", skipping the 1st ".info".
...
Multiple selectors may be specified for a single action using the semicolon (‘‘;’’) separator.  In  this  case  the
selectors  are  processed from left to right, with each selector being able to overwrite the preceding ones.  Using
this behavior you can exclude some priorities from the pattern.
...
# Store critical stuff in critical
#
*.=crit;kern.none            /var/adm/critical
This  will store all messages of priority crit in the file /var/adm/critical, with the exception of any kernel messages
.

看到这里就很明显了,配置文件中
第一行表示facility为auth,authpriv,level是所有级别,处理方案是将消息记录在/var/log/auth.log日志文件中
第二行表示所有facility,所有级别,除了所有facility为auth,authpriv的消息,处理方案是将消息记录在/var/log/syslog日志文件中


理解了上面的内容,以后再调试LDD3中的模块代码,就可以用下面的命令单独开启一个Terminal,从而实时获取打印消息。

$ tail -f /var/log/syslog


补充几点:

1. 如何修改系统默认的日志级别

$ cat /proc/sys/kernel/printk         <= 查看显示日志的默认级别
$ echo 8 > /proc/sys/kernel/printk    <= 修改级别,从而显示所有日志
$ echo 1 > /proc/sys/kernel/printk    <= 恢复默认值

2. 查询系统日志

$dmesg | grep xxx

3. 查询系统日志的传统方法

$tail -f /var/log/message


参考文献

1. http://forum.ubuntu.org.cn

2. http://book.51cto.com/art/200711/59768.htm

3. printk() 使用说明

4. LDD3 4.2 用打印调试

原创粉丝点击