代码:
#include <stdio.h>
#include <unistd.h> /* usleep() */
#include <stdlib.h>
#include <iostream>
#include <fstream>
class SystemRuntimeInfo {
public:
void GetSysStatInfo()
{
system("top -bn 1 -i -c >> sys.txt");
}
void GetCpuInfo()
{
system("sar -P ALL -u 1 5 >> cpu.txt");
// system("");
// system("mpstat 1 5 >> cpu.txt");
// system("dstat -c >> cpu.txt");
}
void GetDiskInfo()
{
system("df -lh >> disk.txt");
}
void GetMemoryInfo()
{
system("vmstat 1 5 >> memroy.txt");
}
void GetIoInfo()
{
system("iostat 1 5 >> io.txt");
}
};
int main()
{
unsigned count = 5;
while (count --> 0)
{
SystemRuntimeInfo aInfo;
std::ofstream outfile;
outfile.open("sys.txt", std::ios::app | std::ios::out);
outfile << '\n';
aInfo.GetSysStatInfo();
outfile << '\n' << std::endl;
outfile.close();
outfile.open("cpu.txt", std::ios::app | std::ios::out);
outfile << '\n';
aInfo.GetCpuInfo();
outfile << '\n' << std::endl;
outfile.close();
outfile.open("disk.txt", std::ios::app | std::ios::out);
outfile << '\n';
aInfo.GetDiskInfo();
outfile << '\n' << std::endl;
outfile.close();
outfile.open("memory.txt", std::ios::app | std::ios::out);
outfile << '\n';
aInfo.GetMemoryInfo();
outfile << '\n' << std::endl;
outfile.close();
usleep(1000);
}
return 0;
}
主要就是使用system()调用shell命令,其中‘>>’ or '>'的意思就是将输出重定向写入到指定的文件中,其区别是:'>'获取的输出会覆盖掉原文件中的内容。
参考资料:
1.https://www.cnblogs.com/Anker/p/3381667.html
2.https://blog.csdn.net/albenxie/article/details/72885951
3.还有几个记不得了,之后也没有找到...sry。。。