windows和Linux的平台下,通过进程名称获取cpu的使用率和内存占用,以及磁盘占用,以及将获取到的数据发出去。

#ifndef RESOURCE_MINITOR_H
#define RESOURCE_MINITOR_H
#include <QObject>
#include <QTimer>
#include <QProcess>
#include <QDebug>
#include <QString>
#if defined(Q_OS_LINUX)
#include "sys/statfs.h"
#else
#pragma comment(lib,"Kernel32.lib")
#pragma comment(lib,"Psapi.lib")
#include <windows.h>
#include <tlhelp32.h>
#include<direct.h>
#include<winternl.h>
#include <psapi.h>
//#include <atlconv.h>
#include <cmath>
#include <string.h>
#endif
 class MySysInfo : public QObject
 {
     Q_OBJECT
 public:
     explicit MySysInfo(QObject *parent = nullptr);
 private slots:
     void GetResource();
 public:
     bool GetMemUsage(double &nMemTotal,double &nMemUsed);
     bool GetNetUsage();
     bool GetDiskSpeed();
     bool GetCpuUsage(double &nCpuRate);
     bool GetdiskSpace(unsigned long &lFreeAll,unsigned long &lTotalAll);
     bool GetPathSpace(const QString & path);
     double FileTimeToDouble(FILETIME &filetime);
 private:
     const int m_timer_interval__ = 1000;
     QTimer monitor_timer__;
     double m_send_bytes__ = 0;
     double m_disk_read__ = 0;
     double m_disk_write__ = 0;
     double m_cpu_total__ = 0;
     double m_cpu_use__ = 0;

     double m_fOldCPUKernelTime_PID,m_foldCPUUserTime_PID,m_fOldCPUKernelTime,m_foldCPUUserTime;

 };
 #endif // RESOURCE_MINITOR_H
#include "mysysinfo.h"
MySysInfo::MySysInfo(QObject *parent) : QObject(parent)
{
    connect(&monitor_timer__, &QTimer::timeout, this, &MySysInfo::GetResource);
    monitor_timer__.start(m_timer_interval__);
}
void MySysInfo::GetResource()
{
    double nCpuRate = 0;
    GetCpuUsage(nCpuRate);
    GetDiskSpeed();
    double nMemTotal;
    double nMemUsed;
    GetMemUsage(nMemTotal,nMemUsed);
    GetNetUsage();
    unsigned long lFreeAll;
    unsigned long lTotalAll;
    GetdiskSpace(lFreeAll,lTotalAll);
    GetPathSpace("/");
    qDebug()<<"\n";
}
bool MySysInfo::GetMemUsage(double &nMemTotal,double &nMemUsed)
{
#if defined(Q_OS_LINUX)
    QProcess process;
    process.start("free -m"); //使用free完成获取
    process.waitForFinished();
    process.readLine();
    QString str = process.readLine();
    str.replace("\n","");
    str.replace(QRegExp("( ){1,}")," ");//将连续空格替换为单个空格 用于分割
    auto lst = str.split(" ");
    if(lst.size() > 6)
    {
        qDebug("mem total:%.0lfMB free:%.0lfMB",lst[1].toDouble(),lst[6].toDouble());
        nMemTotal = lst[1].toDouble();
        nMemUsed = nMemTotal-lst[6].toDouble();
        return true;
    }
    else
    {
        return false;
    }
#else
    MEMORYSTATUSEX memsStat;
        memsStat.dwLength = sizeof(memsStat);
        if(!GlobalMemoryStatusEx(&memsStat))//如果获取系统内存信息不成功,就直接返回
        {
            return false;
        }
        double nMemFree = memsStat.ullAvailPhys/( 1024.0*1024.0 );
        nMemTotal = memsStat.ullTotalPhys/( 1024.0*1024.0 );
        nMemUsed= nMemTotal- nMemFree;
        qDebug("windows:mem total:%.0lfMB,use:%.0lfMB",nMemTotal,nMemUsed);
        return true;
#endif
}
bool MySysInfo::GetNetUsage()
{
#if defined(Q_OS_LINUX)
    QProcess process;
    process.start("cat /proc/net/dev"); //读取文件/proc/net/dev获取网络收发包数量,再除取样时间得到网络速度
    process.waitForFinished();
    process.readLine();
    process.readLine();
    while(!process.atEnd())
    {
        QString str = process.readLine();
        str.replace("\n","");
        str.replace(QRegExp("( ){1,}")," ");
        auto lst = str.split(" ");
        if(lst.size() > 9 && lst[0] == "enp2s0:")
        {
            double recv = 0;
            double send = 0;
            if(lst.size() > 1)
                recv = lst[1].toDouble();
            if(lst.size() > 9)
                send = lst[9].toDouble();
            qDebug("%s 接收速度:%.0lfbyte/s 发送速度:%.0lfbyte/s",lst[0].toStdString().c_str(),(recv - m_recv_bytes__) / (m_timer_interval__ / 1000.0),(send - m_send_bytes__) / (m_timer_interval__ / 1000.0));
            m_recv_bytes__ = recv;
            m_send_bytes__ = send;
        }
    }
#endif
    return true;
}
#if defined(Q_OS_WIN32)
__int64 Filetime2Int64(const FILETIME* ftime)
{
    LARGE_INTEGER li;
    li.LowPart = ftime->dwLowDateTime;
    li.HighPart = ftime->dwHighDateTime;
    return li.QuadPart;
}

__int64 CompareFileTime(FILETIME preTime,FILETIME nowTime)
{
    return Filetime2Int64(&nowTime) - Filetime2Int64(&preTime);
}
#endif
bool MySysInfo::GetCpuUsage(double &nCpuRate)
{
    nCpuRate = -1;
#if defined(Q_OS_LINUX)
    QProcess process;
    process.start("cat /proc/stat");
    process.waitForFinished();
    QString str = process.readLine();
    str.replace("\n","");
    str.replace(QRegExp("( ){1,}")," ");
    auto lst = str.split(" ");
    if(lst.size() > 3)
    {
        double use = lst[1].toDouble() + lst[2].toDouble() + lst[3].toDouble();
        double total = 0;
        for(int i = 1;i < lst.size();++i)
            total += lst[i].toDouble();
        if(total - m_cpu_total__ > 0)
        {
            qDebug("cpu rate:%.2lf%%",(use - m_cpu_use__) / (total - m_cpu_total__) * 100.0);
            m_cpu_total__ = total;
            m_cpu_use__ = use;
            nCpuRate = (use - m_cpu_use__) / (total - m_cpu_total__) * 100.0;
            return true;
        }
    }
#else
    /*windows 获取cpu的使用率
     *
     *
     *
     *
     *
     *
     * /
     */

//        bool res;
//        static FILETIME preIdleTime;
//        static FILETIME preKernelTime;
//        static FILETIME preUserTime;


        HANDLE hEvent;
        FILETIME ftCreatew,ftExit,ftKernel_PID,ftUser_PID;
        int pid = 4116 ;
        hEvent = OpenProcess(PROCESS_ALL_ACCESS,FALSE,pid);
        if(GetProcessTimes(hEvent,&ftCreatew,&ftExit,&ftKernel_PID,&ftUser_PID))
        {
            m_fOldCPUKernelTime_PID = FileTimeToDouble(ftKernel_PID);
            m_foldCPUUserTime_PID = FileTimeToDouble(ftUser_PID);
        }
        FILETIME idleTime;
        FILETIME kernelTime;
        FILETIME userTime;
        if(GetSystemTimes(&idleTime,&kernelTime,&userTime)){
            m_fOldCPUKernelTime = FileTimeToDouble(kernelTime);
            m_foldCPUUserTime = FileTimeToDouble(userTime);
        }
//        WaitForSingleObject(hEvent,500);//等待500毫秒
        Sleep(1000);
        if(GetProcessTimes(hEvent,&ftCreatew,&ftExit,&ftKernel_PID,&ftUser_PID))
        {
            m_fOldCPUKernelTime_PID = FileTimeToDouble(ftKernel_PID)-m_fOldCPUKernelTime_PID;
            m_foldCPUUserTime_PID = FileTimeToDouble(ftUser_PID)-m_foldCPUUserTime_PID;
        }
//        FILETIME idleTime;
//        FILETIME kernelTime;
//        FILETIME userTime;
        if(GetSystemTimes(&idleTime,&kernelTime,&userTime)){
            m_fOldCPUKernelTime = FileTimeToDouble(kernelTime)-m_fOldCPUKernelTime;
            m_foldCPUUserTime = FileTimeToDouble(userTime)-m_foldCPUUserTime;
        }
        else
        {
            nCpuRate = 0;
        }
        nCpuRate = double(m_fOldCPUKernelTime_PID+m_foldCPUUserTime_PID)*100/
                (double)(m_fOldCPUKernelTime+m_foldCPUUserTime);
        QString strvalue = QString::number(nCpuRate,'f',7);
        qDebug()<<"windows:CPU use rate:"<<strvalue<<"%";



//        res = GetSystemTimes(&idleTime,&kernelTime,&userTime);
//        preIdleTime = idleTime;
//        preKernelTime = kernelTime;
//        preUserTime = userTime;
//        hEvent = CreateEvent(nullptr,FALSE,FALSE,nullptr);//初始值为nonsignaled
//        WaitForSingleObject(hEvent,500);//等待500毫秒
//        res = GetSystemTimes(&idleTime,&kernelTime,&userTime);
//        long long idle = CompareFileTime(preIdleTime,idleTime);
//        long long kernel = CompareFileTime(preKernelTime,kernelTime);
//        long long user = CompareFileTime(preUserTime,userTime);
//        nCpuRate =ceil( 100.0*( kernel + user - idle ) / ( kernel + user ) );
//        qDebug()<<"windows:CPU use rate:"<<nCpuRate<<"%";
#endif
    return true;
}
bool MySysInfo::GetDiskSpeed()
{
#if defined(Q_OS_LINUX)
    QProcess process;
    process.start("iostat -k -d");
    process.waitForFinished();
    process.readLine();
    process.readLine();
    process.readLine();
    QString str = process.readLine();
    str.replace("\n","");
    str.replace(QRegExp("( ){1,}")," ");
    auto lst = str.split(" ");
    if(lst.size() > 5)
    {
        qDebug("disk read:%.0lfkb/s disk write:%.0lfkb/s",(lst[4].toDouble() - m_disk_read__ ) / (m_timer_interval__ / 1000.0),(lst[5].toDouble() - m_disk_write__) / (m_timer_interval__ / 1000.0));
        m_disk_read__ = lst[4].toDouble();
        m_disk_write__ = lst[5].toDouble();
        return true;
    }
#endif
    return false;
}
bool MySysInfo::GetdiskSpace(unsigned long &lFreeAll,unsigned long &lTotalAll)
{
#if defined(Q_OS_LINUX)
    QProcess process;
    process.start("df -k");
    process.waitForFinished();
    process.readLine();
    while(!process.atEnd())
    {
        QString str = process.readLine();
        if(str.startsWith("/dev/sda"))
        {
            str.replace("\n","");
            str.replace(QRegExp("( ){1,}")," ");
            auto lst = str.split(" ");
            if(lst.size() > 5)
                qDebug("挂载点:%s 已用:%.0lfMB 可用:%.0lfMB",lst[5].toStdString().c_str(),lst[2].toDouble()/1024.0,lst[3].toDouble()/1024.0);
            lFreeAll += lst[2].toDouble()/1024.0;
            lTotalAll += lst[3].toDouble()/1024.0+lFreeAll;
        }
    }
#else

    static char path[_MAX_PATH];//存储当前系统存在的盘符
    int curdrive = _getdrive();
    lFreeAll = 0UL;
    lTotalAll = 0UL;
    for(int drive = 1; drive <= curdrive; drive++ )//遍历所有盘符
    {
        if( !_chdrive( drive ) )
        {
            sprintf(path, "%c:\\", drive + 'A' - 1 );
            ULARGE_INTEGER caller, total, free;
            WCHAR wszClassName[_MAX_PATH];
            memset(wszClassName,0,sizeof(wszClassName));
            MultiByteToWideChar(CP_ACP,0,path,strlen(path)+1,wszClassName,
                sizeof(wszClassName)/sizeof(wszClassName[0]));
            if (GetDiskFreeSpaceEx(wszClassName, &caller, &total, &free) == 0)
            {
                qDebug()<<"GetDiskFreeSpaceEx Filed!";
                return false;
            }

            double dTepFree = free.QuadPart/( 1024.0*1024.0 );
            double dTepTotal = total.QuadPart/( 1024.0*1024.0 );
            qDebug()<<"Get Windows Disk Information:"<<path<<"--free:"<<dTepFree<<"MB,--total:"<<dTepTotal<<"MB";
            lFreeAll += ceil(dTepFree);
            lTotalAll += ceil(dTepTotal);
        }
    }
    qDebug("Total disk capacity:%lu MB,Free disk capacity:%lu MB",lTotalAll,lFreeAll);
#endif
    return true;
}
bool MySysInfo::GetPathSpace(const QString & path)
{
#if defined(Q_OS_LINUX)
    struct statfs diskInfo;//需要#include "sys/statfs.h"
    statfs(path.toUtf8().data(), &diskInfo);
    qDebug("%s 总大小:%.0lfMB 可用大小:%.0lfMB",path.toStdString().c_str(),(diskInfo.f_blocks * diskInfo.f_bsize)/1024.0/1024.0,(diskInfo.f_bavail * diskInfo.f_bsize)/1024.0/1024.0);
#endif
    return true;
}

double MySysInfo::FileTimeToDouble(FILETIME &filetime)
{
    return (double)(filetime.dwHighDateTime * 4.2949267296E9)+double(filetime.dwLowDateTime);
}

client.h

#ifndef UDPCLIENT_H
#define UDPCLIENT_H

#include <QObject>
#include <QHostAddress>
#include <QUdpSocket>
#include <QDebug>
#include <QTimer>

class UDPClient :QObject
{
    Q_OBJECT
public:
    UDPClient();

    void InitSocket();//初始化UDP套接字

    void InitTimer();//初始化定时器

public slots:
    void SendData();//发送数据

private:
    QUdpSocket *mUdpSocket;//UDP套接字对象
    QHostAddress mGroupAddress;//组播地址
    QTimer *mTimer;//定时器对象
    int mType;//记录UDP消息传送模式 0:单播 1:广播 2:组播(多播)
};

#endif // UDPCLIENT_H

client.cpp

#include "udpclient.h"

#include <QByteArray>
#include <QDebug>
//#include <stdlib.h>
#include <windows.h>

typedef struct Header{

    int channel;
    int type;

}Headr;

typedef struct Msg{

    Header header;
    char content[128];

    friend QDebug operator << (QDebug os, Msg msg){

        os << "(" << " channel:" << msg.header.channel << " type:" << msg.header.type
           << " content:" << msg.content << " )";

        return os;
    }

}Msg;

UDPClient::UDPClient()
{
//    mType = 0;//Unicast
//    mType = 1;//Broadcast
    mType = 2;//Multicast
    InitSocket();
    InitTimer();

}

void UDPClient::InitSocket()
{
    mUdpSocket = new QUdpSocket;//初始化socket
    mGroupAddress.setAddress("239.2.2.222");//设置组播地址
    mUdpSocket->bind(6666);//绑定端口号
    if(mType == 2)
    {
        //组播的数据的生存期,数据报没跨1个路由就会减1.表示多播数据报只能在同一路由下的局域网内传播
        mUdpSocket->setSocketOption(QAbstractSocket::MulticastTtlOption,1);
    }
}

void UDPClient::InitTimer()
{
    mTimer = new QTimer;//初始化定时器
    connect(mTimer,&QTimer::timeout,this,[=]
    {
        SendData();
    });
    mTimer->start(1000);//每隔一秒发送一次数据
}

void UDPClient::SendData()
{
//    QByteArray _data = "hello";
    Header msg;
    msg.channel = 1001;
    msg.type = 1;
//    strcpy(msg.content, "ABCDEFG");

//    qDebug() << msg;
    QByteArray _data;
    _data.append((char*)&msg, sizeof(msg));
    if(mType == 0)//单播
    {
        QHostAddress _peerHostAddress = QHostAddress("10.0.0.177");//对位服务器IP
        quint16 _port = 6666;//对位服务器端口
        if(-1 !=mUdpSocket->writeDatagram(_data.data(),_data.size(),_peerHostAddress,_port))
        {
            qDebug()<< "Unicast ==> Send data : "<< _data<<endl;
        }
        mUdpSocket->flush();
    }
    else if(mType == 1)//广播
    {
        quint16 _port = 6666;//广播端口
        if(-1 !=mUdpSocket->writeDatagram(_data.data(),QHostAddress::Broadcast,_port))
        {
            qDebug()<< "Broadcast ==> Send data : "<< _data<<endl;
        }
        mUdpSocket->flush();
    }
    else if(mType == 2)//组播
    {
        quint16 _port = 8888;//组播端口

        if(-1 != mUdpSocket->writeDatagram(_data.data(),mGroupAddress,_port))
        {
            qDebug()<< "Multicast ==> Send data : "<< _data<<endl;
        }
        mUdpSocket->flush();
    }
    else
    {
        qDebug()<< "mType is error! "<<endl;
        return;
    }


}

server.h

#ifndef UDPSERVER_H
#define UDPSERVER_H

#include <QObject>
#include <QHostAddress>
#include <QUdpSocket>
#include <QDebug>


#ifdef OS_LINUX



#endif

class UDPServer : QObject
{
    Q_OBJECT
public:
    UDPServer();
    void InitSocket();//初始化套接字

public slots:
    void ReadPendingDataframs();//读取消息

private:
    QUdpSocket *mUdpSocket;//UDP套接字
    QHostAddress mGroupAdress;//组播地址
    int mType; //记录UDP消息传送模式 0:单播 1:广播  2:组播(多播)
};

#endif // UDPSERVER_H

server.cpp

#include "udpserver.h"
typedef struct Header{

    int channel;
    int type;

}Headr;

typedef struct Msg{

    Header header;
    char content[128];

    friend QDebug operator << (QDebug os, Msg msg){

        os << "(" << " channel:" << msg.header.channel << " type:" << msg.header.type
           << " content:" << msg.content << " )";

        return os;
    }

}Msg;

UDPServer::UDPServer()
{
//    mType = 0;//Unicast
//    mType = 1;//Broadcast
    mType = 2;//Multicast
    InitSocket();

}

void UDPServer::InitSocket()
{
    //初始化socket,设置组播地址
    mUdpSocket = new QUdpSocket;
    mGroupAdress.setAddress("239.2.2.222");
    if(mType == 0 || mType == 1)
    {
        //绑定本地IP和端口号
        mUdpSocket->bind(6666);
    }
    else if(mType == 2)
    {
        if(mUdpSocket->bind(QHostAddress::AnyIPv4,8888,QUdpSocket::ShareAddress))
        {
            //加入组播地址
            mUdpSocket->joinMulticastGroup(mGroupAdress);
            qDebug()<<("Join Multicast Adrress [")<<mGroupAdress.toString()
                   <<("] Successful!")<<endl;
        }
    }
    else
    {
        qDebug()<< "mType is error! "<<endl;
        return;
    }

    connect(mUdpSocket,&QUdpSocket::readyRead,this,[=]{
        ReadPendingDataframs();
    });
}



void UDPServer::ReadPendingDataframs()
{
    QByteArray _data;
    _data.resize(mUdpSocket->pendingDatagramSize());
    if(mType == 0)//Unicast
    {
        QHostAddress *_peerHostAddress = new QHostAddress("10.0.0.32");
        quint16 _port = 6666;
        while(mUdpSocket->hasPendingDatagrams())
        {
            mUdpSocket->readDatagram(_data.data(),_data.size(),_peerHostAddress,&_port);//接收指定IP和端口的udp报文
            qDebug()<<"Unicast ==> Receive data : "<<QString::fromLatin1(_data)<<endl;
        }
    }
    else if(mType == 1)//Broadcast
    {
        QHostAddress _peerHostAddress;
        quint16 _port;
        while(mUdpSocket->hasPendingDatagrams())
        {
            mUdpSocket->readDatagram(_data.data(),_data.size(),&_peerHostAddress,&_port);//接收同一子网的udp报文
            qDebug()<<"Broadcast ==> Receive data : "<<QString::fromLatin1(_data)<<endl;
        }
    }
    else if(mType == 2)//Multicast
    {
        QHostAddress _peerHostAddress;
        quint16 _port;
        while(mUdpSocket->hasPendingDatagrams())
        {
            mUdpSocket->readDatagram(_data.data(),_data.size(),&_peerHostAddress,&_port);//接收同组的udp报文
            Header *getMsg = (Header*)_data.data();
            Header SSS = *getMsg;
            qDebug()<<SSS.channel<<sizeof(SSS)<<_data.size();

            qDebug()<<"Multicast ==> Receive data : "<<SSS.type<<endl;
        }
    }
    else
    {
        qDebug()<< "mType is error! "<<endl;
        return;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值