六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 34|回复: 0

Linux下类FreeBSD uprintf实现

[复制链接]

升级  14.54%

1227

主题

1227

主题

1227

主题

榜眼

Rank: 8Rank: 8

积分
3727
 楼主| 发表于 2013-1-26 14:58:07 | 显示全部楼层 |阅读模式
uprintf是FreeBSD下内核函数, 作用是将内核信息输出到当前的tty给用户显示, 非常方便. 而linux下无此函数, 不过可以通过借用tty设备来达到目的.

以下是代码实现.
Kernel version: 2.6.28
gcc Version: 4.3.3
#include <linux/module.h>       /* Needed by all modules */#include <linux/kernel.h>       /* Needed for KERN_INFO */#include <linux/init.h>#include <linux/syscalls.h>#include <linux/unistd.h>#include <linux/sched.h>    /* For current */#include <linux/tty.h>      /* For the tty declarations */static void tty_print(const char *str){    struct tty_struct *cur_tty;    // 取得当前的tty    if ( current->signal )        cur_tty = current->signal->tty;    else        cur_tty = NULL;    // 调用当前tty设备驱动write操作    if ( cur_tty ) {        if ( cur_tty->driver ) {            cur_tty->driver->ops->write(                cur_tty,                str,                strlen( str )                );/*            cur_tty->driver->ops->write(                cur_tty,                "\015\012",                2                );*/        }    }}int uprintf(const char *fmt, ...){    char printf_buf[1024];    va_list args;    int printed;    va_start(args, fmt);    printed = vsprintf(printf_buf, fmt, args);    va_end(args);    tty_print( printf_buf );    return 0;}EXPORT_SYMBOL( uprintf );static int __init uprintf_init(void){    uprintf( "hello init\n" );    return 0;}static void __exit uprintf_fini(void){    uprintf( "hello end\n" );}module_init(uprintf_init);module_exit(uprintf_fini);
Makefile
obj-m = uprintf.ouprintf-objs = main.oKVERSION = $(shell uname -r)all:            make -C /lib/modules/$(KVERSION)/build M=$(PWD) modulesclean:            make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean            rm -f Module.markers  modules.order
参考:
Replacing printk's
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表