|
uprintf是FreeBSD下内核函数, 作用是将内核信息输出到当前的tty给用户显示, 非常方便. 而linux下无此函数, 不过可以通过借用tty设备来达到目的.
以下是代码实现.
Kernel version: 2.6.28
gcc Version: 4.3.3
view plaincopy to clipboardprint?
1. #include <linux/module.h> /* Needed by all modules */
2. #include <linux/kernel.h> /* Needed for KERN_INFO */
3. #include <linux/init.h>
4. #include <linux/syscalls.h>
5. #include <linux/unistd.h>
6.
7. #include <linux/sched.h> /* For current */
8. #include <linux/tty.h> /* For the tty declarations */
9.
10.
11. static void tty_print(const char *str)
12. {
13. struct tty_struct *cur_tty;
14.
15. // 取得当前的tty
16. if ( current->signal )
17. cur_tty = current->signal->tty;
18. else
19. cur_tty = NULL;
20.
21. // 调用当前tty设备驱动write操作
22. if ( cur_tty ) {
23. if ( cur_tty->driver ) {
24. cur_tty->driver->ops->write(
25. cur_tty,
26. str,
27. strlen( str )
28. );
29. /*
30. cur_tty->driver->ops->write(
31. cur_tty,
32. \"\\015\\012\",
33. 2
34. );
35. */
36. }
37.
38. }
39.
40. }
41.
42. int uprintf(const char *fmt, ...)
43. {
44. char printf_buf[1024];
45. va_list args;
46. int printed;
47.
48. va_start(args, fmt);
49. printed = vsprintf(printf_buf, fmt, args);
50. va_end(args);
51.
52. tty_print( printf_buf );
53. return 0;
54. }
55.
56. EXPORT_SYMBOL( uprintf );
57. static int __init uprintf_init(void)
58. {
59. uprintf( \"hello init\\n\" );
60. return 0;
61. }
62.
63. static void __exit uprintf_fini(void)
64. {
65. uprintf( \"hello end\\n\" );
66. }
67.
68. module_init(uprintf_init);
69. module_exit(uprintf_fini);
#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
view plaincopy to clipboardprint?
1. obj-m = uprintf.o
2. uprintf-objs = main.o
3.
4. KVERSION = $(shell uname -r)
5. all:
6. make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
7. clean:
8. make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean
9. rm -f Module.markers modules.order |
|