I am trying to read the output of an executed command into a std::string
but for some reason, only the first lines of the file are being assigned.
Here is what I am trying to do
/*SomeClient.cpp*/
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <iterator>
void SomeClient::triggerProcessOutput() const {
std::string runningProcessInfo = getRunningProcessInfo();
// USER PID
}
const std::string SomeClient::getRunningProcessInfo() const {
return getStdOutFromCommand("ps aux");
}
const std::string SomeClient::getStdOutFromCommand(std::string cmd) const {
std::string tmpFileName = std::tmpnam(NULL);
std::system( ( cmd + " > " + tmpFileName ).c_str() ); // I can see the output of the command in the created tmp file.
std::stringstream data;
std::ifstream processInfo(tmpFileName.c_str());
data << processInfo.rdbuf();
return data.str();
/*
//Did not work - Same output
std::string result(std::istreambuf_iterator<char>(std::ifstream(tmpFileName.c_str())
>> std::skipws),
std::istreambuf_iterator<char>());
return result
*/
/*
//Did not work - Same output
std::ifstream file(tmpFileName.c_str());
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
return file_contents;
*/
}
After logging the runningProcessInfo
variable
Output : USER PID
,
Expected output :
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.3 3312 1820 ? Ss Sep20 0:04 /sbin/ss.exe
root 2 0.0 0.0 0 0 ? S Sep20 0:00 [xxxx]
root 3 0.0 0.0 0 0 ? S Sep20 0:02 [xxxrd/0]
root 7 0.0 0.0 0 0 ? S Sep20 0:09 [dfxxxxx]
.
.
.
.
.
.
I have also tried other approaches that are mentioned here, here and here but no success. All the approaches produce the same output mentioned above ( USER PID
).
I am new to C++ and might be missing something obvious. Also, I won't be able to use boost
and popen
for this problem.