fgets不从popen fd读取任何内容

时间:2018-08-29 08:56:00

标签: c++ c file io

ksta命令的输出如下:

PU423E3X16003871# ksta
Radio 1 client count 1
    MAC:4c:66:41:11:5d:a9 ip:60.60.70.6 ip_proto:ip ip_age:130 host:android-8710a239e8a8a97c vci:dhcpcd-5.5.6
        vlanid:0 Auth:Yes channel:136 rate:86Mbps rssi:35dB idle:3600s
        Rx bytes:12715 Tx bytes:4034 Rx rate:86Mbps Tx rate:86Mbps Rx last:130s Tx last:131s
        AssocID:1 Mode:normal Flags:0 PauseCnt:0 intf wl1.1 AssocTime: 2316s

下面是一个解析器,它运行ksta命令并从输出中获取8个指定字段的值。对于每个值,它运行CFG_set函数来注册变量。

现在的问题是从fd中什么也没读。第一次调用fgets()时,buf似乎为空,并且该函数退出时并未实际读取任何内容。

有时,当我运行这段代码时,绝对没有任何内容打印到调试文件中。

有人看到我的代码有什么问题吗?

static int set_sta_info()
{
    FILE * fd;
    FILE * fd_test;
    FILE * fd3;
    char buf[CMD_BUF_LENGTH];
    char* key_val;
    char* start;
    char* value;
    char* key;
    int i;
    char* keys[8] = {"MAC", "ip", "host", "vci", "vlanid", "Auth", "rssi", "AssocTime"};
    //fd = popen("ksta > /tmp/ksta_output.txt", "r");
    fd = popen("cw_diag ksta", "r");
    fd_test = fopen("/tmp/sta_info_debug.txt", "a");
    fprintf(fd_test, "entering set_sta_info()\n");
    if (!fd) return -1;
    // Station Mac, Ip, Hostname, vlanid, Auth, Rate, rssi, interface (wl1.1), Assoc Time.
    while (1)
    {   fprintf(fd_test, "inside while loop");
        buf[0] = 0;
        for (i = 0; i < CMD_BUF_LENGTH; i++){
            buf[i] = 0;
        }
        fgets(buf, sizeof(buf), fd);
        fprintf(fd_test, " line is %s\n", buf);
        if (buf[0] == 0) break;
        fprintf(fd_test, "buf is not empty, didn't break\n");
        key_val = strtok(buf, ' ');
        fprintf(fd_test, "line 2808.\n");
        while (key_val) {
            fprintf(fd_test, "current element examining: %s\n", key_val);
            for (i = 0; i < 8; i++){
                fprintf(fd_test, "looking at key %s\n", keys[i]);
                if (strstr(key_val, keys[i])){
                    fprintf(fd_test, "%s is found in %s\n", keys[i], key_val);
                    start = strstr(buf, ':');
                    if (!start){
                        fprintf(fd_test, "but, there is no :, so skipped.\n");
                        continue;
                    }
                    start ++;
                    while (*start && (*start == ' ' || *start == '\t')) start++;
                    fprintf(fd_test, "the word to be copied is %s\n", start);
                    strncpy(value, start, MAX_NAME_LEN);
                    CFG_set_by_name(keys[i], value);
                    fprintf(fd_test, "key is %s, value is %s\n", keys[i], value);
                }
            }
            key_val = strtok(NULL, ' ');
        }
    }
    fclose(fd);
         fclose(fd_test);
    return 0;
}

0 个答案:

没有答案