首先,引入内核tty控制台库:
1 |
#include <linux/tty.h> |
然后,编写输出函数:
1 2 3 4 5 6 7 8 9 10 |
static void print_string(char *str) { struct tty_struct *my_tty; my_tty = current->signal->tty; if (my_tty != NULL) { my_tty->ops->write(my_tty,str,strlen(str)); //Linux 6.0 内核写法 } } |
最后,在需要的位置调用函数;
1 |
print_string("Hello from kernel"); |
完整代码示例(根据pid修改进程nice内核模块):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/moduleparam.h> #include <linux/sched.h> #include <linux/tty.h> #include <linux/string.h> static int mypid; static long nice; struct task_struct * task; struct pid * kpid; module_param(mypid,int,0644); module_param(nice,long,0644); static void print_string(char *str) { struct tty_struct *my_tty; my_tty = current->signal->tty; if (my_tty != NULL) { my_tty->ops->write(my_tty,str,strlen(str)); } } static int nice_init(void){ char info[128]={0}; int nice_new; int nice_old; kpid = find_get_pid(mypid); task = pid_task(kpid,PIDTYPE_PID); nice_old = task_nice(task); set_user_nice(task,nice); nice_new = task_nice(task); sprintf(info,"pid %d 's nice set to %d,(previous is %d)",mypid,nice_new,nice_old); print_string(info); return 0; } static void nice_exit(void){ printk(KERN_ALERT"goodbye\n"); } module_init(nice_init); module_exit(nice_exit); MODULE_LICENSE("GPL"); |