Using the SO post here: How do I read the results of a system() call in C++?
I was able to write a function that runs an arbitrary system command and returns any output as a string:
string pipeAndGetResults(string cmd)
{
const char* ccmd = cmd.c_str();
FILE* stream = popen( ccmd, "r" );
std::ostringstream output;
while( !feof( stream ) && !ferror( stream ))
{
char buf[128];
int bytesRead = fread( buf, 1, 128, stream );
output.write( buf, bytesRead );
}
string result = output.str();
boost::trim(result);
return result;
}
I have always used this for system commands that "instantly" produce a value. My question is whether this function will also work if cmd takes some time to run, say a minute, and then writes the results. I had problems doing something similar with Python's pexpect
; it was timing out while waiting for a result if cmd took awhile, and I could not upper bound the runtime of cmd. I believe that question simplifies to whether cmd always writes eof
after however long it takes to run?