#include <stdio.h>
#include <signal.h>
#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>
#include <list>
using namespace std;
std::string getValueBySystemCommand(std::string strCommand){
//printf("-----%s------\n",strCommand.c_str());
std::string strData = "";
FILE * fp = NULL;
char buffer[128];
fp=popen(strCommand.c_str(),"r");
if (fp) {
while(fgets(buffer,sizeof(buffer),fp)){
strData.append(buffer);
}
pclose(fp);
}
//printf("-----%s------ end\n",strCommand.c_str());
return strData;
}
int runSystemCommand(std::string strCommand){
// printf("-----%s------\n",strCommand.c_str());
return system(strCommand.c_str());
}
string trim(string str)
{
if (str.empty())
{
return str;
}
str.erase(0,str.find_first_not_of(" "));
str.erase(str.find_last_not_of(" ") + 1);
return str;
}
std::vector<std::string> split(std::string str, std::string pattern)
{
string::size_type pos;
vector<string> result;
str += pattern;
int size = str.size();
for (int i = 0; i < size; i++) {
pos = str.find(pattern, i);
if (pos < size) {
string s = str.substr(i, pos - i);
result.push_back(s);
i = pos + pattern.size() - 1;
}
}
return result;
}
float getcpugap(){
std::string strRes = getValueBySystemCommand("top -b -n 1 |grep Cpu | cut -d \",\" -f 1 | cut -d \":\" -f 2");
strRes = trim(strRes);
printf("--%s-- strRes.size : %lu \n", strRes.c_str(),strRes.length());
std::vector<std::string> vecT = split(strRes," ");
if (vecT.size() == 2){
printf("%s\n", vecT.at(0).c_str());
return atof(vecT.at(0).c_str());
}
return 0;
}
int main ()
{
printf("start \n");
signal(SIGCHLD, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
signal(SIGILL, SIG_IGN);
// std::string pstr = "%Cpu(s): 0.4 us, 0.9 sy, 0.0 ni, 98.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st";
float cpugap =getcpugap();
printf("%f\n", cpugap);
return 0;
}