基于 https://blog.youkuaiyun.com/yangyang031213/article/details/79023536 修改测试通过
#include <QProcess>
void MainWindow::get_procinfo()
{
QProcess process;
process.start("free -m"); //使用free完成获取
process.waitForFinished();
process.readLine();
QString str = process.readLine();
str.replace("\n","");
str.replace(QRegExp("( ){1,}")," ");//将连续空格替换为单个空格 用于分割
QStringList lst = str.split(" ");
if(lst.size() > 3)
{
QString str2;
//str2.sprintf("mem total:%.0lfMB free:%.0lfMB",lst[1].toDouble(),lst[3].toDouble());
double mem_rate =(lst[1].toDouble() -lst[3].toDouble()) / lst[1].toDouble() * 100.0;
str2.sprintf("mem rate:%.2lf%%",mem_rate);
ui->label_2->setText(str2);
//qDebug("mem total:%.0lfMB free:%.0lfMB",lst[1].toDouble(),lst[3].toDouble());
qDebug("mem rate:%.2lf%%",mem_rate);
}
void MainWindow::get_cpu()
{
QProcess process;
double cpu_total=0;
double cpu_use=0;
process.start("cat /proc/stat");
process.waitForFinished();
QString str = process.readLine();
str.replace("\n","");
str.replace(QRegExp("( ){1,}")," ");
QStringList lst = str.split(" ");
if(lst.size() > 3)
{
double use = lst[1].toDouble() + lst[2].toDouble() + lst[3].toDouble();
double total = 0;
double cpu_rate=0;
for(int i = 1;i < lst.size();++i)
total += lst[i].toDouble();
if(total - m_cpu_total > 0)
{
QString str1;
cpu_rate = (use - cpu_use) / (total - cpu_total) * 100.0;
str1.sprintf("cpu rate:%.2lf%%",cpu_rate);
qDebug("cpu rate:%.2lf%%",cpu_rate);
ui->label_4->setText(str1);
m_cpu_total = total;
m_cpu_use = use;
}
}
}