簡體   English   中英

使用 popen() 在 C 程序中讀取 avrdude 的 output

[英]Read output of avrdude in C program using popen()

我需要使用相同的程序來使用avrdude對多個不同的微控制器進行編程。 為此,我需要識別連接的微控制器的設備簽名以使用正確的avrdude命令。 我發現在軟件中執行此操作的唯一方法是使用不正確的微控制器調用avrdude ,並讀取它給出設備簽名的結果。 我正在嘗試使用popen()來讀取 avrdude 的avrdude ,但我什么也沒得到。 這是我用來測試popen()的代碼:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char ch, avrBuffer[100];
    FILE *avr;

    avr = popen("sudo avrdude -n -q -p x192d3 -c avrisp2", "r");

    if(avr == NULL) {
        printf("Unable to open avrdude");
        return(0);
    }

    fgets(avrBuffer, 100, avr);
    printf("Buffer: %s \n", avrBuffer);

    pclose(avr);
    return EXIT_SUCCESS; 
}

運行它給了我這個結果:

avrdude: AVR device initialized and ready to accept instructions
avrdude: Device signature = 0x000000 (retrying)
avrdude: Device signature = 0x1e9749 (probably x192d3)

avrdude done.  Thank you.

Buffer:  

如您所見,緩沖區沒有添加任何內容。 但是,當我切換到不同的命令時:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char ch, avrBuffer[100];
    FILE *avr;

    avr = popen("uname", "r");

    if(avr == NULL) {
        printf("Unable to open avrdude");
        return(0);
    }

    fgets(avrBuffer, 100, avr);
    printf("Buffer: %s \n", avrBuffer);

    pclose(avr);
    return EXIT_SUCCESS;
}

我得到了這個結果,這是我所期待的:

Buffer: Linux

我是否使用了popen()錯誤,或者我應該以不同的方式執行此操作? 如果重要的話,我會在 Raspberry Pi 上運行該程序。

根據-l logfile選項的文檔措辭,這些消息可能歸類為“診斷輸出”,因此寫入stderr ,而不是popen捕獲的stdout

解決此問題的一種方法是將avrdudestderr重定向到其stdout 例如,您可以 append 2>&1popen的第一個參數的末尾:

avr = popen("sudo avrdude -n -q -p x192d3 -c avrisp2 2>&1", "r");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM