Dragon Wish Dragon Wish - 2 months ago 19
C++ Question

C++: _popen infinite loop (Windows)

I'm trying to code an application to infinitely check the ping to a server using _popen but when I run the application for a while the function (_popen) starts returning NULL until I restart it. Why would this be happening? How should I go about fixing it?

FILE *fin = _popen("ping 104.160.131.1", "r");
while (fin == NULL) {
std::cout << "If this takes too long restart application";
fin = _popen("ping 104.160.131.1", "r");
system("cls");
}

Answer

The code shown leaks file descriptors because you don't have a corresponding _pclose() call, which would eventually cause the behavior you're describing.

FILE *fin = _popen("ping 104.160.131.1", "r");
while (fin == nullptr) {
    std::cout << "If this takes too long restart application";
    fin = _popen("ping 104.160.131.1", "r");
    system("cls");
}
//...
_pclose(fin);
Comments