![](/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.