Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c - Why printk doesn't print message in kernel log(dmesg)

I wrote small kernel module code as mentioned below, I am testing it in ubuntu 14.04

#include <linux/module.h> 
#include <linux/version.h>
#include <linux/kernel.h>
#include <linux/init.h>

int init_mod_func(void)
{
    printk(KERN_INFO "My module inserted
 ");
    return 0;
}

void cleanup_mod_func(void)
{
    printk(KERN_INFO "My module removed
 ");
}

module_init(init_mod_func);
module_exit(cleanup_mod_func);


MODULE_AUTHOR("Ankur");
MODULE_DESCRIPTION("TEST MODULE");
MODULE_LICENSE("GPL");

Now when I compile and insert above module using insmod I don't see printk message in the dmesg. However after module removal using rmmod I see both the printk messages.

With closure look, I found out that it is happening because of space after in the printk.
However I don't get why it is like that.

ankur:~/temp/tmp$ 
ankur:~/temp/tmp$ 
ankur:~/temp/tmp$ sudo dmesg -C /dev/null
ankur:~/temp/tmp$ 
ankur:~/temp/tmp$ 
ankur:~/temp/tmp$ sudo insmod testmod.ko 
ankur:~/temp/tmp$ dmesg
ankur:~/temp/tmp$ 
ankur:~/temp/tmp$ sudo rmmod testmod
ankur:~/temp/tmp$ dmesg
[ 4062.140441] My module inserted
[ 4062.140441]  
[ 4073.324994] My module removed
[ 4073.324994]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The kernel log ring buffer behaves as if it were line-buffered, as it can be seen in the implementation:

  • in vprintk_emit you can see how it marks a buffer to be flushed/buffered based on the existence of a trailing newline

  • in log_output you can see the actual code which takes care of flushing or buffering the message

As it is evident, your messages do not contain trailing newlines. Had you deleted the trailing space, you would see the messages in the kernel log after they had been flushed in the printk call(s).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...