2

I am creating a tool for managing my VMs on my ESXi servers. I am parsing the output from popen() from running vim-cmd commands.

The issue is when calling fgets() in a function outside of main(). If I call it inside of main() it works without issue.

Code:

int main() {
    FILE* fp = NULL;
    char path[255] = {0};
    char* cmd = "vim-vmd vmsvc/getsummary";

    fp = popen(cmd, "r");
    if (fp == NULL) {
        return -1;
    }

    int cnt = 0;
    while(fgets(path, 255, fp) != NULL) {
        printf("%s\n", path);
    }
    pclose(fp);
    return 0;
}

This will work. But if I place all of that code into a function and then call that function from main() it will seg fault on fgets().

This crashes...

void myfunc() {
    FILE* fp = NULL;
    char path[255] = {0};
    char* cmd = "vim-vmd vmsvc/getsummary";

    fp = popen(cmd, "r");
    if (fp == NULL) {
        return;
    }

    int cnt = 0;
    while(fgets(path, 255, fp) != NULL) {
        printf("%s\n", path);
    }
    pclose(fp);
    return;
}

int main() {
    myfunc();
    return 0;
}

I am building this on Ubuntu 12.04 since the glibc version is 2.14 on this version and my ESXi server is 2.17.

James Risner
  • 5,451
  • 11
  • 25
  • 47

0 Answers0