模块中printk信息打印到指定文件 终端 网络

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

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,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上测试过了
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值