linux平台关于内存,cpu,连接数,流量监控(一)
生活随笔
收集整理的這篇文章主要介紹了
linux平台关于内存,cpu,连接数,流量监控(一)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
linux平臺關(guān)于內(nèi)存,cpu,連接數(shù),流量監(jiān)控(一)
本文為監(jiān)控linux平臺機(jī)器及進(jìn)程cpu,內(nèi)存,連接數(shù),流量監(jiān)控程序,其他平臺請自適應(yīng)。
//.h/** Copyright (c/c++) <2017.03.24> <zwg> * Function ? * Monitor the CPU memory connections flow response time program * 命令: * 根據(jù)名稱查看pid :ps aux | grep processname * 查看cpu內(nèi)存:ps -o %cpu,rss,%mem,pid,tid -mp pid //watch ifconfig 例如:ps -o %cpu,rss,%mem,pid,tid -mp 108809 * 查看網(wǎng)卡流量:watch more /proc/net/dev * 查看連接數(shù):netstat -nat|grep -i "port"|wc -l * 1. 查看物理CPU的個數(shù)#cat /proc/cpuinfo |grep "physical id"|sort |uniq|wc -l * 2. 查看邏輯CPU的個數(shù)#cat /proc/cpuinfo |grep "processor"|wc -l * 3. 查看CPU是幾核#cat /proc/cpuinfo |grep "cores"|uniq * 4. 查看CPU的主頻#cat /proc/cpuinfo |grep MHz|uniq[@more@] */#ifndef __LVS_MONITOR_H__ #define __LVS_MONITOR_H__#include <iostream>? #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <sys/types.h> #include <dirent.h> #include <sys/time.h> #include <map> #include <sys/stat.h> #include <unistd.h>#define Printf_INFO ? ? ? ? ? //是否輸出日志 #define _LINE_LENGTH 300?using namespace std;class cMonitor;class cMonitor { public://構(gòu)造函數(shù)cMonitor();//析構(gòu)函數(shù)virtual ~cMonitor();//得到邏輯CPU的個數(shù)//參數(shù): ?//返回值:邏輯CPU的個數(shù)int GetLogicCpuNum();//得到cpu使用率內(nèi)存//參數(shù): ?獲取的cpu;mem;傳入的pid;tid(可填-1);?//返回值:1 :成功 0 : 失敗int GetCpuMemUsage(float * cpu,int * mem ,const int pid,int tid = -1);//得到連接數(shù)根據(jù)port;//參數(shù): port;//返回值:連接數(shù)int GetConnectionsByPort(const int port);//查看網(wǎng)卡流量//參數(shù): netDeviceName;unBW;nInLB;nOutLB,nInLastBytes是當(dāng)前上行數(shù)據(jù),nInLastBytes是當(dāng)前下行數(shù)據(jù)//返回值:1 :成功 0 : 失敗int GetNetworkTraffic(const string netDeviceName,const unsigned int unBW,const unsigned int nMilisecond,?long * nInLastByte,long * nOutLastByte,unsigned int * nInLB,unsigned int * nOutLB);//計算固定時間帶寬包括上行和下行//參數(shù): netDeviceName;unBW;nInLB;nOutLB;存儲文件句柄pfile;//返回值:1 :成功 0 : 失敗int GetTimerNetworkTraffic(const string netDeviceName,const unsigned int unBW,const unsigned int nMilisecond,?unsigned int * nInLB,unsigned int * nOutLB,void * pfile); private: public: private: };#endif //.cpp#include "Monitor.h"cMonitor::cMonitor() { }cMonitor::~cMonitor() { }int cMonitor::GetLogicCpuNum() {char cmdline[100] = {0};?FILE * file = NULL;?char line[_LINE_LENGTH] = {0};int CpuNum = 0;//cat /proc/cpuinfo |grep "processor"|wc -lsprintf(cmdline, "cat /proc/cpuinfo |grep \"processor\"|wc -l"); ?file = popen(cmdline, "r");?if (file == NULL) ?{? #ifdef Printf_INFOprintf("file == NULL\n");? #endifreturn 0;?}?if (fgets(line, _LINE_LENGTH, file) != NULL) ??{ ?sscanf(line, "%d", &CpuNum );?}?else?{//命令錯誤 #ifdef Printf_INFOprintf("GetLogicCpuNum : Command or Parameter fail\n");? #endif}pclose(file);?return CpuNum; }int cMonitor::GetCpuMemUsage(float * cpu,int * mem ,const int pid,int tid) {int ret = 0;?char cmdline[100] = {0};?FILE * file = NULL;?char line[_LINE_LENGTH] = {0};?float l_cpuPrec = 0.0;?int l_mem = 0;?float l_memPrec = 0;?int l_pid = 0;?int l_tid = 0;?//ps -o %cpu,rss,%mem,pid,tid -mp pidsprintf(cmdline, "ps -o %%cpu,rss,%%mem,pid,tid -mp %d", pid); ?file = popen(cmdline, "r");?if (file == NULL) ?{? #ifdef Printf_INFOprintf("file == NULL\n");? #endifreturn 0;?}?if (fgets(line, _LINE_LENGTH, file) != NULL) ? ? ? //第一行是 %CPU ?RSS ? %MEM ? PID ? TID?{?? ?if (fgets(line, _LINE_LENGTH, file) != NULL) ? //第二行是 0.0 ?2356 ? 0.0 ? 19736 ? -{ ?sscanf(line, "%f %d %f %d -", &l_cpuPrec, &l_mem, &l_memPrec, &l_pid );?*cpu = l_cpuPrec;?//*mem = l_mem/1024; ?//具體內(nèi)存占用情況*mem = (int )l_memPrec; //內(nèi)存占用百分比(取整)if( tid == -1 )?{ret = 1;?}else?{?while( fgets(line, _LINE_LENGTH, file) != NULL )?{?sscanf( line, "%f - - - %d", &l_cpuPrec, &l_tid );?if( l_tid == tid )?{? #ifdef Printf_INFOprintf("cpuVal is tid:%d\n",tid);? #endif*cpu = l_cpuPrec;?ret = 1;?break;?}?}?if( l_tid != tid )?{//進(jìn)程 tid 不存在 #ifdef Printf_INFOprintf("TID not exist\n");? #endif}}?}?else?{//進(jìn)程pid 不存在 #ifdef Printf_INFOprintf("GetCpuMemUsage : PID not exist\n"); #endifreturn 0;}}?else?{//命令錯誤 #ifdef Printf_INFOprintf("GetCpuMemUsage : Command or Parameter fail\n");? #endif}pclose(file);?//獲取cpu核數(shù)int cpunum = GetLogicCpuNum(); #ifdef Printf_INFOprintf("LogicCpu nuclear : %d\n ",cpunum); #endif*cpu = l_cpuPrec/cpunum;return ret;? }int cMonitor::GetConnectionsByPort(const int port) {char cmdline[100] = {0};?FILE * file = NULL;?char line[_LINE_LENGTH] = {0};?int Connections = 0;//netstat -nat|grep -i "port"|wc -l//ps -ef|grep "processname"|wc -lsprintf(cmdline, "netstat -nat|grep -i \"%d\"|wc -l", port); ?file = popen(cmdline, "r");?if (file == NULL) ?{? #ifdef Printf_INFOprintf("file == NULL\n");? #endifreturn 0;?}?if (fgets(line, _LINE_LENGTH, file) != NULL) ?{ ?sscanf(line, "%d", &Connections);?}?else?{//進(jìn)程 port 不存在 #ifdef Printf_INFOprintf("GetConnectionsByPort : port not exist\n"); ? #endif}pclose(file);?return Connections;? }int cMonitor::GetNetworkTraffic(const string netDeviceName,const unsigned int unBW,const unsigned int nMilisecond,?long * nInLastByte,long * nOutLastByte,unsigned int * nInLB,unsigned int * nOutLB) {FILE * fp = NULL;//watch more /proc/net/devfp = fopen("/proc/net/dev","r");if(fp){char szLine[1024] = {'\0'};int64_t nR = 0;int64_t nT = 0;int n = 0;while(fgets(szLine,sizeof(szLine),fp)){n++;if(n > 2){char szeth[256] = {'\0'};sscanf(szLine,"%[^:]",szeth);printf("GetNetworkTraffic::szeth :%s\n",szeth);sscanf(szLine+strlen(szeth)+1,"%ld %*u %*u %*u %*u %*u %*u %*u %ld",&nR,&nT);if((strncasecmp(netDeviceName.c_str(),szeth + 0,netDeviceName.size())==0) ||(strncasecmp(netDeviceName.c_str(),szeth + 1,netDeviceName.size())==0)||(strncasecmp(netDeviceName.c_str(),szeth + 2,netDeviceName.size())==0)) //比較字符串前幾個字符{if((*nInLastByte) == 0 && (*nOutLastByte) == 0){(*nInLastByte) = nR;(*nOutLastByte) = nT;fclose(fp);return 0;}int allBW = unBW;if (nMilisecond == 0 || allBW ==0){(*nInLastByte) = nR;(*nOutLastByte) = nT;fclose(fp);return 0;}double fltInTemp = (nR -(*nInLastByte)) * 8.0 /1024; ?//轉(zhuǎn)換成kbpsdouble fltOutTemp = (nT - (*nOutLastByte)) * 8.0 /1024;//轉(zhuǎn)換成kbpsfloat ? fltInFlow = fltInTemp /(nMilisecond / 1000);//轉(zhuǎn)換成秒的流量float ? fltOutFlow = fltOutTemp /(nMilisecond / 1000);//轉(zhuǎn)換成秒的流量 #ifdef Printf_INFOprintf("***************** nR : %ld\n",nR);printf("***************** nT : %ld\n",nT);printf("***************** nInLastByte : %ld\n",*nInLastByte);printf("***************** nOutLastByte : %ld\n",*nOutLastByte);printf("***************** fltInTemp : %lf\n",fltInTemp);printf("***************** fltOutTemp : %lf\n",fltOutTemp); #endif ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?*nInLB = (unsigned int)(fltInFlow);*nOutLB = (unsigned int)(fltOutFlow);(*nInLastByte) = nR;(*nOutLastByte) = nT;break;}else{printf("netDeviceName error\n");}}}fclose(fp);}else{ #ifdef Printf_INFOprintf("open /proc/net/dev file fail\n"); #endifreturn 0;}return 1; }int cMonitor::GetTimerNetworkTraffic(const string netDeviceName,const unsigned int unBW,const unsigned int nMilisecond,?unsigned int * nInLB,unsigned int * nOutLB,void * pfile) {int ret = 0;long ?nInLastByte = 0;?? ??? ??? ??? ?//流量用獲取第二次流量減去獲取第一次流量long ?nOutLastByte = 0;?? ??? ??? ??? ?//流量用獲取第二次流量減去獲取第一次流量struct timeval tv_begin; ? ? ? ? ? ?//當(dāng)前時間起始struct timeval tv_end; ? ? ? ? ? ? ?//當(dāng)前時間結(jié)束//獲取開始時間gettimeofday(&tv_begin,NULL);//第一次獲取帶寬的數(shù)值GetNetworkTraffic(netDeviceName,unBW,nMilisecond,?&nInLastByte,&nOutLastByte,nInLB,nOutLB);printf("nInLastByte %ld nOutLastByte :%ld\n",nInLastByte,nOutLastByte);while(1){//獲取結(jié)束時間gettimeofday(&tv_end,NULL);int nDeff = ((tv_begin.tv_sec - tv_end.tv_sec) * 1000000 + (tv_begin.tv_usec - tv_end.tv_usec) ) / 1000000; ?//轉(zhuǎn)化成微妙if (nDeff > nMilisecond *1000){//第二次獲取帶寬的數(shù)值GetNetworkTraffic(netDeviceName,unBW,nMilisecond,?&nInLastByte, &nOutLastByte,nInLB,nOutLB);printf("nInLastByte %ld nOutLastByte :%ld\n",nInLastByte,nOutLastByte);break;}else{usleep(1000);continue;}}//寫到文件中if (pfile != NULL){char fileinfo[256] = {0};sprintf(fileinfo,"netDeviceName :%s unBW :%dM time : %dms nInLB : %uKbps nOutLB : %uKbps\n",netDeviceName.c_str(),unBW,nMilisecond,*nInLB,*nOutLB);int writesize = fwrite(fileinfo, strlen(fileinfo), 1, (FILE *)pfile);fflush((FILE *)pfile);}return ret; } //main.cpp//下面是測試 int main() {cMonitor *pmonitor = new cMonitor();//step1 測試cpu 內(nèi)存float ncpu = 0.0; ? ? ? ? //cpuint nmem = 0; ? ? ? ? ? ? //內(nèi)存int npid = 0; ? ? ? ? ? ? //pidint ntid = -1; ? ? ? ? ? ?//tidnpid = 108809;pmonitor->GetCpuMemUsage(&ncpu,&nmem,npid,ntid);printf("Pid : %d %%CPU:%.1f\tMEM:%d\n",npid,ncpu ,nmem);?//step2 測試連接數(shù)int nport = 0;int connectnum = 0;nport = 1936;connectnum = pmonitor->GetConnectionsByPort(nport);printf("nport: %d connectnum : %d\n",nport,connectnum);//step3 測試帶寬網(wǎng)卡流量string netDeviceName = "eth2"; ? ?//網(wǎng)卡設(shè)備號//string netDeviceName = "enp0s31f6"; //網(wǎng)卡設(shè)備號int unBW = 0;?? ??? ??? ??? ??? ??? ?//設(shè)置帶寬最大值(M)unsigned int nInLB = 0;?? ??? ??? ??? ?//上行流量unsigned int nOutLB = 0;?? ??? ??? ?//下行流量long long nInLB_all = 0; ? ? ? ? ? ?//上行流量總值long long nOutLB_all = 0; ? ? ? ? ? //下行流量總值long long nLB_timer = 0; ? ? ? ? ? ?//流量總共時間unsigned int nMilisecond = 0;?? ??? ?//毫秒數(shù)nMilisecond = 1000; ? ? ? ? ? ? ? ? //1秒unBW = 500; ? ? ? ? ? ? ? ? ? ? ? ? //500mFILE * pnetworkfp = NULL; ? ? ? ? ? //存儲帶寬的pnetworkfp = fopen("network.log","wb");//持續(xù)獲取流量信息 #if 1while(1){pmonitor->GetTimerNetworkTraffic(netDeviceName,unBW,nMilisecond,?&nInLB,&nOutLB,pnetworkfp);printf("netDeviceName :%s unBW :%dM time : %dms nInLB : %uKbps nOutLB : %uKbps\n",netDeviceName.c_str(),unBW,nMilisecond,nInLB,nOutLB);nInLB_all += nInLB;?nOutLB_all += nOutLB;nLB_timer += nMilisecond;printf("****************Average LB : in : %dKbps out : %dKbps\n",nInLB_all/(nLB_timer/nMilisecond),nOutLB_all/(nLB_timer/nMilisecond));}; #elsepmonitor->GetTimerNetworkTraffic(netDeviceName,unBW,nMilisecond,?&nInLB,&nOutLB,pnetworkfp);printf("netDeviceName :%s unBW :%dM time : %dms nInLB : %uKbps nOutLB : %uKbps\n",netDeviceName.c_str(),unBW,nMilisecond,nInLB,nOutLB); #endif//關(guān)閉文件if (pnetworkfp){fclose(pnetworkfp);pnetworkfp = NULL;}delete pmonitor;pmonitor = NULL; }
程序運行效果
---------------------?
作者:zhuweigangzwg?
來源:CSDN?
原文:https://blog.csdn.net/zhuweigangzwg/article/details/66971357?
版權(quán)聲明:本文為博主原創(chuàng)文章,轉(zhuǎn)載請附上博文鏈接!
總結(jié)
以上是生活随笔為你收集整理的linux平台关于内存,cpu,连接数,流量监控(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: FFMPEG进阶系列01-ffplay命
- 下一篇: Nginx Rtmp Module -