關閉Linux中的串口打印

項目中用到串口通信,但是這個串口也用於控制檯。爲了保證串口通信時不能有控制檯發出的消息,需要關閉打印。

在測試過程中發現,有三種類型的打印,一是uboot的打印,在Starting kernel ...之前的打印都是;二是prink的打印,linux kernel不能用printf,對應的輸出函數是printk,它的實現在kernel/printk.c中;三是應用層的printf。


1、去掉printk打印

在linux內核中的/kernel目錄下printk.c文件中有一個函數:
static void __call_console_drivers(unsigned long start, unsigned long end)
{
struct console *con;
for (con = console_drivers; con; con = con->next) {
  if ((con->flags & CON_ENABLED) && con->write)
   con->write(con, &LOG_BUF(start), end - start);
}
}

去掉如下兩行重新編譯內核即可:
   if ((con->flags & CON_ENABLED) && con->write)
   con->write(con, &LOG_BUF(start), end - start);


2、標準輸出、標準錯誤輸出重定向

int main() {
    int pid = 0;
    // fork a worker process
    if (pid = fork()) {
        // wait for completion of the child process
        int status; 
        waitpid(pid, &status, 0);
    }
    else {
        // open /dev/null
        int fd_null = open("/dev/null", O_RDWR);
        if(dup2(fd_null, 1) == -1)
            return 1;
        if(dup2(fd_null, 2) == -1)
             return 1;
         XX_run();
 }
    return 0;
}

我將標準輸出和錯誤輸出重定向到/dev/null中
 

如果我沒有將輸出重定向,只是關閉輸出,close(1) close(2),程序經常出現錯誤,這個還需要繼續研究。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章