首页 > 解决方案 > fgets 没有从 popen fd 中读取任何内容

问题描述

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;
}

标签: c++cfileio

解决方案


推荐阅读