我正在使用 Intel Edison 和 SensorTag。为了通过 BLE 获取温度数据,有一堆命令。当我将 popen 定义为:
popen(command,"w");
大多数情况下,代码都能正常工作。 (由于我无法控制响应而导致的其他时间崩溃,我认为是延迟问题。)
但是,当我想控制命令/控制台响应时(例如在建立蓝牙连接时进入下一行,如果不尝试再次连接等),我无法读取响应。我的“数据”变量没有改变。
我也尝试了其他模式的“popen”,但它们会产生运行时错误。
这是我使用的代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int endsWith (char* base, char* str) {
int blen = strlen(base);
int slen = strlen(str);
return (blen >= slen) && (0 == strcmp(base + blen - slen, str));
}
FILE* get_popen(char* command, int close, int block) {
FILE *pf;
char data[512];
// Setup our pipe for reading and execute our command.
pf = popen(command,"w");
// Error handling
if (block == 1) {
// Get the data from the process execution
char* result;
do {
result=fgets(data, 512 , stderr);
if (result != NULL) {
printf("Data is [%s]\n", data);
}
} while (result != NULL);
// the data is now in 'data'
}
if (close != 0) {
if (pclose(pf) != 0)
fprintf(stderr," Error: Failed to close command stream \n");
}
return pf;
}
FILE* command_cont_exe(FILE* pf, char* command, int close, int block) {
char data[512];
// Error handling
if (pf == NULL) {
// print error
return NULL;
}
fwrite(command, 1, strlen(command), pf);
fwrite("\r\n", 1, 2, pf);
if (block == 1) {
// Get the data from the process execution
char* result;
do {
result=fgets(data, 512 , stderr);
if (result != NULL) {
printf("Data is [%s]\n", data);
}
} while (result != NULL);//
}
// the data is now in 'data'
if (close != 0) {
if (pclose(pf) != 0)
fprintf(stderr," Error: Failed to close command stream \n");
}
return pf;
}
int main()
{
char command[50];
sprintf(command, "rfkill unblock bluetooth");
get_popen(command, 1, 0);
printf("Working...(rfkill)\n");
sleep(2);
sprintf(command, "bluetoothctl 2>&1");
FILE* pf = get_popen(command, 0, 1);
printf("Working...(BT CTRL)\n");
sleep(3);
sprintf(command, "agent KeyboardDisplay");
command_cont_exe(pf, command, 0, 1);
printf("Working...(Agent)\n");
sleep(3);
//Main continues...
最佳答案
您不能使用 popen
执行此操作,但可以使用 fork
、exec
和 pipe
构建程序。最后一个打开两个文件描述符,它们是相关的:父级与管道的连接,以及子级的连接。要与子进程建立双向连接,您必须两次调用pipe
。
pipe
打开的文件描述符没有缓冲,因此您可以使用read
和write
来与 child 沟通(而不是 fgets
和 fprintf
)。
有关示例和讨论,请参阅
关于c - 如何在 C 中使用 "popen"写入和读取同一文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32474138/