1. 程式人生 > >linux重定向串列埠列印到telnet

linux重定向串列埠列印到telnet

/************************************************************
Copyright (C), 2017, Leon, All Rights Reserved.
FileName: console_redirect.c
Description: console輸出重定向
Author: Leon
Version: 1.0
Date: 2017-2-6 15:33:12
Function:
History:
<author>    <time>  <version>   <description>
 Leon
************************************************************/ /* 核心的列印不能重定向過來,應用層列印可以重定向列印過來 檢視核心的列印,cat /proc/kmsg,在輸出完緩衝區內容後,會阻塞卡住,核心有新的輸出時會繼續輸出。 如果要把核心列印到telnet,那麼需要修改printk.c。 kernel和user空間下都有一個console,關係到kernel下printk的方向和user下printf的方向,實現差別很大。 kernel下的console是輸入輸出裝置driver中實現的簡單的輸出console,只實現write函式,並且是直接輸出到裝置。
user空間下的console,實際就是tty的一個特殊實現,大多數操作函式都繼承tty,所以對於console的讀寫,都是由kernel的tty層來最終傳送到裝置。 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/ioctl.h> #include <unistd.h> int main(int argc, char *argv[]) { int tty = -1
; char *tty_name = NULL; if(argc < 2) { printf("miss argument\n"); return 0; } /* 獲取當前tty名稱 */ tty_name = ttyname(STDOUT_FILENO); printf("tty_name: %s\n", tty_name); if(!strcmp(argv[1], "on")) { /* 重定向console到當前tty */ tty = open(tty_name, O_RDONLY | O_WRONLY); ioctl(tty, TIOCCONS); perror("ioctl TIOCCONS"); } else if(!strcmp(argv[1], "off")) { /* 恢復console */ tty = open("/dev/console", O_RDONLY | O_WRONLY); ioctl(tty, TIOCCONS); perror("ioctl TIOCCONS"); } else { printf("error argument\n"); return 0; } close(tty); return 0; }