I have an Ubuntu C++ application that executes shell commands by calling popen(). The popen() call works great usually but sometimes it will fail and will indicate error 12 'Cannot allocate memory'.
I know that the system is not even close to being out of memory, so that's not the problem. I know that the process has roughly 250 files open, which is far less than the OPEN_MAX value of 1024.
What else could be the problem?
I've read elsewhere that I could be at the STREAM_MAX limit (which is 16), but I don't know how to check whether or not this is actually the case. Any help would be very much appreciated!
Here is the complete code:
// Format the command to get the number of files open in this process
char szCommand[1024];
memset(&(szCommand[0]), 0, sizeof(szCommand));
snprintf(szCommand, sizeof(szCommand) - 1, "lsof -p %i | wc -l", static_cast<int>(getpid()));
// A string to capture the output
std::string szTotalOutput("");
// Execute the command
FILE *pFile = popen(szCommand, "r");
// If the open was successful
if (pFile)
{
// A text buffer to capture output
char szOutput[2048];
memset(&(szOutput[0]), 0, sizeof(szOutput));
// Get the output
while (fgets(szOutput, static_cast<int>(sizeof(szOutput) - 1), pFile))
{
// Add to the total output
szTotalOutput += std::string(szOutput);
}
// Close the file
pclose(pFile);
}
// Or, if the open failed
else
{
// An error string
char szError[2048];
memset(&(szError[0]), 0, sizeof(szError));
// If we have a good error
if (errno != 0)
{
// Format the error string
snprintf(szError, sizeof(szError) - 1, "popen failed with error %i '%s'", errno, strerror(errno));
}
// Or, if we don't have a good error
else
{
// Format the error string
snprintf(szError, sizeof(szError) - 1, "popen failed but errno was not set");
}
// Print this error message to the console window
printf("Error: File %s line %i: %s\n", __FILE__, __LINE__, szError);
}
EDIT:
I've found that if I re-enable swap (which was previously disabled) then the issue doesn't happen. But ultimately I need for this to work with swap disabled.