1.
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/syscalls.h>
#include <asm/unistd.h>
#include <asm/uaccess.h>
#define MY_FILE "/root/LogFile"
char buf[128];
struct file *file = NULL;
static int __init init(void)
{
mm_segment_t old_fs;
printk("Hello, I'm the module that intends to write messages to file./n");
if(file == NULL)
file = filp_open(MY_FILE, O_RDWR | O_APPEND | O_CREAT, 0644);
if (IS_ERR(file)) {
printk("error occured while opening file %s, exiting.../n", MY_FILE);
return 0;
}
sprintf(buf,"%s", "The Messages.");
old_fs = get_fs();
set_fs(KERNEL_DS);
file->f_op->write(file, (char *)buf, sizeof(buf), &file->f_pos);
set_fs(old_fs);
return 0;
}
static void __exit fini(void)
{
if(file != NULL)
filp_close(file, NULL);
}
module_init(init);
module_exit(fini);
MODULE_LICENSE("GPL");
2.
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/tty.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("mq110");
static void print_string(char *str)
{
struct tty_struct *my_tty;
my_tty = current->signal->tty;
if (my_tty != NULL)
{
my_tty->driver->write(my_tty,0,str,strlen(str));
my_tty->driver->write(my_tty,0,"/015/013",2);
}
}
static int __init print_string_init(void)
{
print_string("Hello world!");
return 0;
}
static void __exit print_string_exit(void)
{
print_string("Goodbye world!");
}
module_init(print_string_init);
module_exit(print_string_exit);
[/CODE]
我一般用putty登陆 编写kernel module. printk信息都存在/var/log/message里了.~
用这个程序就能显示在屏幕上了.你可以把print_string 符号导出来.
3.
修改一下/etc/syslog.conf 文件
#kern.* /dev/console
你打印的东西可能是某个级别的信息。比如说debug,这用printk 可以控制 。
那么就写程
kern.debug /var/log/kern_debug.log
-------------------------
printk(KERN_ALERT "Hello, world/n");
对应
/etc/syslog.conf 中的
kern.alert /kernel.txt
实验成功,修改后要执行
server syslogd restart 重启日志服务。
此方法等于用日志服务帮你做这个事情。该信息用
dmesg 命令也可以看到。
本文介绍如何在Linux内核中编写模块并利用日志系统进行信息记录与屏幕显示,包括使用printk函数控制日志级别、配置syslog.conf文件、以及通过dmesg命令查看日志信息。

936

被折叠的 条评论
为什么被折叠?



