printk 僅記錄系統日誌,無法直接顯示於使用者終端。替代方案:透過 current 指標取得目前進程的 tty_struct,再呼叫其驅動程式的 write 函數直接向終端寫入字串。適用 X11 xterm、telnet、序列埠等所有終端類型,模組卸載後除錯尤為重要。
print_string 函數/* printk.c - 向當前終端輸出文字 */
#include <linux/kernel.h>
#include <linux/module.h>
#if CONFIG_MODVERSIONS==1
#define MODVERSIONS
#include <linux/modversions.h>
#endif
#include <linux/sched.h> /* for current */
#include <linux/tty.h> /* for tty declarations */
void print_string(char *str) {
struct tty_struct *my_tty = current->tty;
if (my_tty != NULL) { /* 守護進程無終端,需判空 */
(*(my_tty->driver).write)(my_tty, 0, str, strlen(str));
(*(my_tty->driver).write)(my_tty, 0, "\015\012", 2); /* CR+LF 換行 */
}
}
int init_module() {
print_string("Module Inserted");
return 0;
}
void cleanup_module() {
print_string("Module Removed");
}
tty,直接寫入會導致崩潰\015)與 LF(\012),Unix 單用 LF 會導致下一行從原欄位開始而非行首