![](/img/trans.png)
[英]Python Popen output to a c program, fget read the same stdin in a loop
[英]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
。
解決此問題的一種方法是將avrdude
的stderr
重定向到其stdout
。 例如,您可以 append 2>&1
到popen
的第一個參數的末尾:
avr = popen("sudo avrdude -n -q -p x192d3 -c avrisp2 2>&1", "r");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.