I have a C++ application that periodically calls the following function in order to run a shell command and return the output:
string run_shell_command(const string& command) {
    array<char, 128> buffer;
    string response;
    FILE* pipe = popen(command.c_str(), "r");
    if (!pipe) {
        cerr << "popen failed: " << command << endl;
        return "";
    }
    while (fgets(buffer.data(), 128, pipe) != NULL) {
        response += buffer.data();
    }
    pclose(pipe);
    return response;
}
These calls to run_shell_command usually succeed when the application starts, but after a while, the popen calls start to fail. Note that once this happens, I can still run the shell commands successfully if I do so manually in a terminal. When I tried to look this problem up, some people say that being out of memory or having too many open files can cause the problem, but I don't believe that is currently the case. For example, these outputs were generated just now, while the popen calls have been failing:
~$ free -h
              total        used        free      shared  buff/cache   available
Mem:            31G         25G        220M        2.6G        5.0G        2.3G
Swap:            0B          0B          0B
~$ ulimit -Sn
15000000
~$ ulimit -Hn
15000000
~$ sudo lsof | wc -l
190121
Any ideas? Thanks!
Edit: The errno is 12 and strerror(errno) is "Cannot allocate memory"
Edit: When the application is not running, here is how the memory looks:
$ free -h
              total        used        free      shared  buff/cache   available
Mem:            31G        209M         26G        2.6G        4.2G         27G
Swap:            0B          0B          0B
