mmdev 发表于 2013-1-26 14:58:07

Linux下类FreeBSD uprintf实现

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;    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.markersmodules.order
参考:
Replacing printk's
页: [1]
查看完整版本: Linux下类FreeBSD uprintf实现