Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1520133
  • 博文数量: 399
  • 博客积分: 8508
  • 博客等级: 中将
  • 技术积分: 5302
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-14 09:28
个人简介

能力强的人善于解决问题,有智慧的人善于绕过问题。 区别很微妙,小心谨慎做后者。

文章分类

全部博文(399)

文章存档

2018年(3)

2017年(1)

2016年(1)

2015年(69)

2013年(14)

2012年(17)

2011年(12)

2010年(189)

2009年(93)

分类: LINUX

2009-12-15 13:51:38

有的时候调试内核程序,经常要将信息打印到其他地方如指定文件或终端还有网络,  网络的话dreanice版主写过个netconsole我这里就不说了...

打印到文件:

CODE:
#include
#include
#include
#include
#include
#include
#include
#include
#include

#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");

打印到终端:

CODE:
#include
#include
#include
#include
#include
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,str,strlen(str));
        my_tty->driver->write(my_tty,"\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);

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 命令也可以看到。

代码在Centos5.3   2.6.18上测试过了
阅读(891) | 评论(0) | 转发(0) |
0

上一篇: 内核模块中对文件的读写

下一篇:假金币

给主人留下些什么吧!~~