I am running MacOS and want to execute the "ps aux" command and get its output through my application. I have written a method which executes commands using popen function:
std::string exec(const char* cmd) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!2");
try {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
I have a loop that is constantly running the exec("ps aux") function. The problem is that the pipe from popen is not closed which I have checked using "lsof" command from the terminal. After 20 or so seconds, there are like 300 opened file descriptors by the application which prevents the application from opening more pipes (running the "ps aux" command) from the loop.
What I have discovered, is that the exec function works fine for other commands (the pipe gets closed correctly), for example "netstat", so it must be something in the "ps aux" command that's preventing the pipe to close.
I have searched a lot about that issue, but haven't found any solution. Can somebody please point me in the right direction?
Thank you!