Dragon Wish
Dragon Wish

Reputation: 25

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

Upvotes: 0

Views: 233

Answers (1)

kfsone
kfsone

Reputation: 24249

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

Upvotes: 2

Related Questions