天天看點

Linux printf 輸出 重定向輸出 無法列印問題分析以及解決方法1 說明2 原因分析3 解決方法4 測試結果

1 說明

有時候,在linux 環境下,使用printf 無法列印資訊,導緻調試很不友善。

2 原因分析

2.1 沒有重新整理緩沖區

預設Linux 設定了列印緩沖功能,當列印緩沖區未滿情況下,不列印。如果需要列印,增加fflush(stdout) 語句,用于重新整理緩沖區,即可列印。

2.2 程序關閉了标準輸入輸出功能。

在系統或者程序中,關閉了printf功能,将輸入輸出重定向到 /dev/null 中,是以printf的輸出,都輸出到/dev/null,自然無法列印資訊。

檢視方法: 1、ps 檢視調用printf的程序号,如程序号為200

2、進入程序号的檔案說明檔案夾

cd /proc//fd
           

3、檢視檔案屬性

# ls -al
dr-x------     root     root              Apr  : .
dr-xr-xr-x     root     root              Apr  : ..
lrwx------     root     root             Apr  :  -> /dev/null
lrwx------     root     root             Apr  :  -> /dev/null
lrwx------     root     root             Apr  :  -> /dev/null
           

從中可以看到 0、1、2 檔案都被指向 “dev/null”

shell 中運作的程序,預設會有3個檔案描述符存在(0、1、2)

0 ——— 與程序的标準輸入相關聯。

1 ——– 與程序的标準輸出相關聯。

2 ——— 與程序的标準錯誤輸出相關聯。

0、1、2都被指向 /dev/null,是以 輸入、輸出、标準錯誤的資訊都指向null(也就是所謂的黑洞),往null 丢資料,自然什麼都沒有顯示。

3 解決方法

重定向輸入、輸出、錯誤資訊。

例如,本裝置的輸出序列槽為 /dev/console,則進行設定的代碼 test.c 如下

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

// set the stdio, can support printf function to display message.
static void set_stdio(void)
{
    int fd = -;

    fd = open("/dev/console", O_RDWR);
    if (fd < )
    {
        fprintf(stderr, "errno=%d (%s)\n", errno, strerror(errno));
        return;
    }
    dup2(fd, );    // standrad input set 
    dup2(fd, );    // standrad ouput set
    dup2(fd, );    // standrad error set
    close(fd);
}


int main(int argc, char** argv)
{
    set_stdio();
    printf("--test printf function--\n");
    fflush(stdout);

    return ;
}
           

4 測試結果

  1. 編譯
arm-none-linux-gnueabi-gcc -o test test.c
           

2、将程式下載下傳到嵌入式開發闆,運作測試結果

# ./set 
--test printf function--
           

繼續閱讀