如何在C

时间:2015-09-09 08:03:36

标签: c pipe popen intel-edison

我正在使用英特尔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...

2 个答案:

答案 0 :(得分:2)

您无法使用popen执行此操作,但可以使用forkexecpipe构建程序。最后打开两个相关的文件描述符:父管道与管道的连接以及子连接。要与子进程建立双向连接,您必须使用两次调用pipe

pipe打开的文件描述符不是缓冲,因此您可以使用readwrite与孩子进行通信(而不是{{ 1}}和fgets)。

有关示例和讨论,请参阅

答案 1 :(得分:1)

不幸的是,您只能在一个方向上使用sendError。要获得双向通信,您需要为stdin和stdout创建两个带有popen()的匿名管道,并使用pipe()将它们分配给文件句柄0和1。

有关详细信息,请参阅http://tldp.org/LDP/lpg/node11.html