1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > linux系统状态(磁盘大小 内存 进程 cpu使用率 网络连接)

linux系统状态(磁盘大小 内存 进程 cpu使用率 网络连接)

时间:2023-12-27 01:02:10

相关推荐

linux系统状态(磁盘大小 内存 进程 cpu使用率 网络连接)

分享一下自己做的一个获取Linux系统状态的类(c++)(代码整理后的,在物理机上测试可以,在vm虚拟机上测试,磁盘计算有问题)

头文件

#ifndefLINUXSERVERSTATE_H#defineLINUXSERVERSTATE_H#include<sys/types.h>#include<unistd.h>#include<string>#include<vector>#include<pthread.h>#include<map>usingstd::string;usingstd::vector;usingstd::map;#pragmapack(push)#pragmapack(8)structSysMemInfo{unsignedlongtotal;//单位:Munsignedlongfree;//单位:M};structSysDiskInfo{stringname;//sda1,sad2等等unsignedlongtotal;//单位:M,不包括交换分区、CDROM等unsignedlongfree;//单位:M};structSysNetInfo{floatsend;//kbfloatrecv;//kbfloattotal;//kb};structSysProcInfo{stringname;//进程名字intpid;//进程idintcpu;//cpu使用率longmem;//内存使用,单位Kb,linux内存指的是vmrss,即程序正在使用的物理内存,-1表示未获取到或获取错误};structSysProcTimeInfo{unsignedlonguser;//进程在用户态执行的时间unsignedlongkernel;//进程在内核态执行的时间};//linuxsrc目录中的include/net/tcp_states.h,source目录一般位于/usr/src/linux*目录中enumSysNetState{TCP_ESTABLISHED=1,TCP_SYN_SENT,TCP_SYN_RECV,TCP_FIN_WAIT1,TCP_FIN_WAIT2,TCP_TIME_WAIT,TCP_CLOSE,TCP_CLOSE_WAIT,TCP_LAST_ACK,TCP_LISTEN,TCP_CLOSING,/*Nowavalidstate*/TCP_MAX_STATES/*Leaveattheend!*/};enumSockType{UNKNOWN=0,TCP,UDP,TCP6,UDP6};structSysNetConnInfo{intid;SockTypeprotocol;std::stringlocalAddr;intlocalPort;std::stringremoteAddr;intremotePort;SysNetStatestate;};#pragmapack(pop)voidget_netstat(unsignedlong&inOctets,unsignedlong&outOctets,time_t&sysTime);voidget_cpuusage(unsignedlong&cpuTime,unsignedlong&idleTime);classLinuxServerState;voidget_procinfo(LinuxServerState*pMain,map<pid_t,SysProcTimeInfo>&procTimeInfo);void*CPUNetProcessCount(void*arg);classLinuxServerState{public:LinuxServerState();virtual~LinuxServerState();intGetMemInfo(SysMemInfo&memInfo);intGetDiskInfo(vector<SysDiskInfo>&diskInfo,unsignedlong&total,unsignedlong&available);//返回cpu的利用率,返回-1表示超时或者其他错误intGetCpuUsage();//sysnetinfoSysNetInfoGetNetInfo();//processinfovoidGetProcInfo(vector<SysProcInfo>&procinfo);//netconnectioninfovoidGetNetConnectionInfo(vector<SysNetConnInfo>&netConnInfo);private:voidinitialize();friendvoid*CPUNetProcessCount(void*arg);friendvoidget_procinfo(LinuxServerState*pMain,map<pid_t,SysProcTimeInfo>&procTimeInfo);intm_cpuUsage;//多个CPU的总的使用率pthread_mutex_tm_mutex;SysNetInfom_netInfo;pthread_tm_countThread;vector<SysProcInfo>*m_procinfo_cal;vector<SysProcInfo>*m_procinfo;void*m_threadRet;LinuxServerState(constLinuxServerState&other);virtualLinuxServerState&operator=(constLinuxServerState&other);virtualbooloperator==(constLinuxServerState&other)const;boolm_running;};#endif

源文件

#include"sys_stat.h"#include<sys/sysinfo.h>//getmemInfo#include<stdio.h>#include<stdlib.h>#include<fstream>#include<climits>#include<cstring>#include<time.h>#include<dirent.h>#include<errno.h>#include<iostream>#include<fcntl.h>#include<sys/types.h>#include<sys/stat.h>#include<netinet/in.h>#include<sys/socket.h>#include<arpa/inet.h>#include<algorithm>usingnamespacestd;voidget_netstat(unsignedlong&inOctets,unsignedlong&outOctets,time_t&sysTime){unsignedlonginNoRoutes=0,inTruncPkts=0;unsignedlonginMcastPkts=0,outMcastPkts=0;unsignedlonginBcastPkts=0,outBcastPkts=0;unsignedlonginMcastOctets=0,outMcastOctets=0;unsignedlonginBcastOctets=0,outBcastOctets=0;fstreamfProcNetStat("/proc/net/netstat",ios_base::in);charbufNetStat[2048]={'\0'},ipExt[16]={'\0'};while(!fProcNetStat.eof()){fProcNetStat.getline(bufNetStat,2048);if(strncasecmp(bufNetStat,"tcpext",6)==0)continue;if(strncasecmp(bufNetStat,"ipext",5)==0){fProcNetStat.getline(bufNetStat,2048);sscanf(bufNetStat,"%s%ld%ld%ld%ld%ld%ld%ld%ld%ld%ld%ld",ipExt,&inNoRoutes,&inTruncPkts,&inMcastPkts,&outMcastPkts,&inBcastPkts,&outBcastPkts,&inOctets,&outOctets,&inMcastOctets,&outMcastOctets,&inBcastOctets,&outBcastOctets);sysTime=time(NULL);break;}}}voidget_cpuusage(unsignedlong&cpuTime,unsignedlong&idleTime){fstreamfProcStat("/proc/stat",ios_base::in);charcpubuf[8]={'\0'};unsignedlonguserT=0,niceT=0,systemT=0,idleT=0;unsignedlongioT=0,irqT=0,softirqT=0;fProcStat>>cpubuf>>userT>>niceT>>systemT>>idleT>>ioT>>irqT>>softirqT;cpuTime=userT+niceT+systemT+idleT+ioT+irqT+softirqT;idleTime=idleT;}voidget_procinfo(LinuxServerState*pMain,map<pid_t,SysProcTimeInfo>&procTimeInfo){structdirent*ent=NULL;char*endptr=NULL;DIR*pDirProc=opendir("/proc");longutime=0,stime=0;if(pDirProc==NULL)return;chardirName[256]={'\0'};chartmpbuf[2048]={'\0'};if(pMain->m_procinfo_cal==NULL)return;pMain->m_procinfo_cal->clear();while((ent=readdir(pDirProc))!=NULL){longpidNum=strtol(ent->d_name,&endptr,10);if(pidNum==LONG_MAX||pidNum==LONG_MIN||endptr==ent->d_name)continue;fstreamfPidStat,fPidMem;inti=0;SysProcTimeInfotmpProcTimeInfo;SysProcInfotmpProcInfo;snprintf(dirName,256,"%s%d%s","/proc/",pidNum,"/stat");try{fPidStat.open(dirName,ios_base::in);}catch(std::exception&e){continue;}fPidStat>>tmpbuf;//获取pidi++;fPidStat>>tmpbuf;//获取进程名字,名字由"()"包括i++;//processnameif(strlen(tmpbuf)>2)tmpProcInfo.name=string(tmpbuf).substr(1,strlen(tmpbuf)-2);elsecontinue;for(;i<14;i++)fPidStat>>tmpbuf;//14项表示utime,15项表示stimefPidStat>>utime;i++;fPidStat>>stime;i++;tmpProcTimeInfo.user=utime;tmpProcTimeInfo.kernel=stime;//processcpuusagemap<pid_t,SysProcTimeInfo>::iteratorit=procTimeInfo.find((pid_t)pidNum);if(it==procTimeInfo.end()){procTimeInfo.insert(pair<pid_t,SysProcTimeInfo>(pidNum,tmpProcTimeInfo));tmpProcInfo.cpu=0;}else{tmpProcInfo.cpu=utime+stime-it->second.kernel-it->second.user;if(tmpProcInfo.cpu>100)tmpProcInfo.cpu=100;if(tmpProcInfo.cpu<0)tmpProcInfo.cpu=0;it->second.kernel=stime;it->second.user=utime;}utime=0;stime=0;tmpProcInfo.pid=pidNum;//processmemchar*pstrtolong;memset(dirName,'\0',128);snprintf(dirName,128,"%s%d%s","/proc/",pidNum,"/status");fPidMem.open(dirName,ios_base::in);while(!fPidMem.eof()){fPidMem>>tmpbuf;if(strncasecmp(tmpbuf,"vmrss",5)==0){fPidMem>>tmpbuf;unsignedlongvmrss=strtol(tmpbuf,&pstrtolong,10);if(vmrss==LONG_MAX||vmrss==LONG_MIN||pstrtolong==tmpbuf){tmpProcInfo.mem=-1;}elsetmpProcInfo.mem=vmrss;if(0==pthread_mutex_trylock(&pMain->m_mutex)){pMain->m_procinfo_cal->push_back(tmpProcInfo);pthread_mutex_unlock(&pMain->m_mutex);}break;}}memset(dirName,'\0',256);memset(tmpbuf,'\0',2048);}closedir(pDirProc);pDirProc=NULL;if(0==pthread_mutex_trylock(&pMain->m_mutex)){std::swap(pMain->m_procinfo_cal,pMain->m_procinfo);pthread_mutex_unlock(&pMain->m_mutex);}}void*CPUNetProcessCount(void*arg){LinuxServerState*pMain=(LinuxServerState*)arg;unsignedlonginOctets=0,outOctets=0;time_tsysTime;unsignedlongcpuTime=0,idleTime=0;map<pid_t,SysProcTimeInfo>procTimeInfo;while(pMain->m_running){//cputotalusageunsignedlongcpuTimeNow=0,idleTimeNow=0;intcpu=0;get_cpuusage(cpuTimeNow,idleTimeNow);cpu=100-(idleTimeNow-idleTime)*100/(cpuTimeNow-cpuTime);idleTime=idleTimeNow;cpuTime=cpuTimeNow;if(0==pthread_mutex_trylock(&pMain->m_mutex)){pMain->m_cpuUsage=cpu;pthread_mutex_unlock(&pMain->m_mutex);}//else暂时不处理//netstatunsignedlonginOctetsTmp=0,outOctetsTmp=0;time_ttimeNow=time(NULL);get_netstat(inOctetsTmp,outOctetsTmp,timeNow);SysNetInfotmpNetInfo;tmpNetInfo.recv=(inOctetsTmp-inOctets)/1024/(timeNow-sysTime);tmpNetInfo.send=(outOctetsTmp-outOctets)/1024/(timeNow-sysTime);tmpNetInfo.total=tmpNetInfo.recv+tmpNetInfo.send;sysTime=timeNow;inOctets=inOctetsTmp;outOctets=outOctetsTmp;if(0==pthread_mutex_trylock(&pMain->m_mutex)){pMain->m_netInfo=tmpNetInfo;pthread_mutex_unlock(&pMain->m_mutex);}//procinfoget_procinfo(pMain,procTimeInfo);sleep(1);}returnNULL;}LinuxServerState::LinuxServerState(){m_cpuUsage=0;m_countThread=0;m_threadRet=NULL;m_netInfo.total=0;m_netInfo.recv=0;m_netInfo.send=0;m_procinfo_cal=newvector<SysProcInfo>();m_procinfo=newvector<SysProcInfo>();m_running=true;initialize();}LinuxServerState::LinuxServerState(constLinuxServerState&other){}LinuxServerState::~LinuxServerState(){m_running=false;if(m_countThread!=0)pthread_join(m_countThread,NULL);pthread_mutex_destroy(&m_mutex);if(m_procinfo!=NULL)deletem_procinfo;if(m_procinfo_cal!=NULL)deletem_procinfo_cal;}LinuxServerState&LinuxServerState::operator=(constLinuxServerState&other){return*this;}boolLinuxServerState::operator==(constLinuxServerState&other)const{///TODO:return...;}voidLinuxServerState::initialize(){pthread_mutex_init(&m_mutex,NULL);pthread_create(&m_countThread,NULL,&CPUNetProcessCount,this);}intLinuxServerState::GetCpuUsage(){timespectmp;tmp.tv_nsec=0;tmp.tv_sec=1;intcpu=0;if(0==pthread_mutex_timedlock(&m_mutex,&tmp)){cpu=m_cpuUsage;pthread_mutex_unlock(&m_mutex);}if(cpu>100)return100;if(cpu<0)return0;returncpu;}intLinuxServerState::GetMemInfo(SysMemInfo&memInfo){structsysinfotmp;intret=sysinfo(&tmp);if(ret==0){memInfo.free=(unsignedlong)tmp.freeram/(1024*1024);memInfo.total=(unsignedlong)tmp.totalram/(1024*1024);}returnret;}intLinuxServerState::GetDiskInfo(std::vector<SysDiskInfo>&diskInfo,unsignedlong&total,unsignedlong&available){total=0;available=0;charbuf[128]={'\0'};stringfileName;char*p;fstreamfProc("/proc/partitions",ios_base::in);unsignedlongtotal2=0,free2=0,sumTotal=0,sumFree=0;intmajor=0,minor=0;//首先计算总大小及各个分区的大小,包括交换分区,然后用df命令获取可用空间while(!fProc.eof()){fProc>>fileName;total2=strtol(fileName.c_str(),&p,10);if(total2==0)continue;elseif(total2==LONG_MAX||total2==LONG_MIN||p==fileName.c_str())returntotal2;else{major=total2;fProc>>minor;fProc>>total2;fProc>>fileName;SysDiskInfotmp;tmp.total=(unsignedlong)(total2/1024);tmp.free=0;tmp.name=fileName;diskInfo.push_back(tmp);if((fileName.find("sd")!=string::npos||fileName.find("hd")!=string::npos)&&!(fileName[fileName.size()-1]>='0'&&fileName[fileName.size()-1]<='9'))sumTotal+=tmp.total;fileName.clear();}}//获取可用空间constchar*command="df";constchar*type="r";FILE*pFile=popen(command,type);charbuf2[1024]={'\0'};charfilesys[64]={'\0'},usage[8]={'\0'},mountedon[64]={'\0'};unsignedlongkblocks=0,used=0,available2=0;if(pFile==NULL)return-1;vector<SysDiskInfo>::iteratorit;while(!feof(pFile)){if(fgets(buf2,1024,pFile)==NULL)break;sscanf(buf2,"%s%ld%ld%ld%s%s",filesys,&kblocks,&used,&available2,usage,mountedon);stringff(filesys);if(ff.rfind("/")==string::npos)continue;for(it=diskInfo.begin();it!=diskInfo.end();it++){if(it->name==ff.substr(ff.rfind("/")+1)){it->free=(unsignedlong)(available2/1024);sumFree+=it->free;}}memset(buf2,'\0',1024);memset(filesys,'\0',64);memset(mountedon,'\0',64);memset(usage,'\0',8);kblocks=0;used=0;available2=0;}pclose(pFile);total=sumTotal;available=sumFree;return0;}SysNetInfoLinuxServerState::GetNetInfo(){SysNetInfotmpNetInfo;tmpNetInfo.recv=0;tmpNetInfo.send=0;tmpNetInfo.total=0;timespectmp;tmp.tv_nsec=0;tmp.tv_sec=1;if(0==pthread_mutex_timedlock(&m_mutex,&tmp)){tmpNetInfo=m_netInfo;pthread_mutex_unlock(&m_mutex);}returntmpNetInfo;}voidLinuxServerState::GetProcInfo(std::vector<SysProcInfo>&procinfo){timespectmp;tmp.tv_nsec=0;tmp.tv_sec=1;if(0==pthread_mutex_timedlock(&m_mutex,&tmp)){if(m_procinfo==NULL)return;procinfo=*m_procinfo;pthread_mutex_unlock(&m_mutex);}}voidLinuxServerState::GetNetConnectionInfo(std::vector<SysNetConnInfo>&netConnInfo){inti=0,id=0;charbuf[1024]={'\0'};while(i++<4){fstreamfInfo;SockTypestateType=UNKNOWN;if(i==1){fInfo.open("/proc/net/tcp",ios_base::in);stateType=TCP;}elseif(i==2){fInfo.open("/proc/net/udp",ios_base::in);stateType=UDP;}elseif(i==3){fInfo.open("/proc/net/tcp6",ios_base::in);stateType=TCP6;}elseif(i==4){fInfo.open("/proc/net/udp6",ios_base::in);stateType=UDP6;}if(stateType==UNKNOWN)continue;while(!fInfo.eof()){SysNetConnInfotmpConnInfo;charsl[6]={'\0'},localaddr[32]={'\0'},remoteaddr[32]={'\0'};fInfo.getline(buf,1024);unsignedlongllocal=0,lremote=0;intlocalPort=0,remotePort=0,st=0;intret;if(i==1||i==2){ret=sscanf(buf,"%s%x:%x%x:%x%x",sl,&llocal,&localPort,&lremote,&remotePort,&st);if(ret!=6)continue;in_addrtmpAddr;tmpAddr.s_addr=llocal;tmpConnInfo.localAddr=inet_ntoa(tmpAddr);tmpAddr.s_addr=lremote;tmpConnInfo.remoteAddr=inet_ntoa(tmpAddr);}elseif(i==3||i==4){ret=sscanf(buf,"%s%32s:%x%32s:%x%x",sl,&localaddr,&localPort,&remoteaddr,&remotePort,&st);if(ret!=6)continue;chartmp[64]={'\0'};intpos=0;for(intj=0;j<32;j++){tmp[pos++]=localaddr[j];if((j%4)==3&&j!=31)tmp[pos++]=':';}tmpConnInfo.localAddr=string(tmp);memset(tmp,'\0',64);pos=0;for(intj=0;j<32;j++){tmp[pos++]=remoteaddr[j];if((j%4)==3&&j!=31)tmp[pos++]=':';}tmpConnInfo.remoteAddr=string(tmp);}tmpConnInfo.localPort=localPort;tmpConnInfo.remotePort=remotePort;tmpConnInfo.id=id++;tmpConnInfo.protocol=stateType;tmpConnInfo.state=(SysNetState)st;netConnInfo.push_back(tmpConnInfo);}fInfo.close();}}

测试文件

#include<iostream>#include"sys_stat.h"usingnamespacestd;intmain(intargc,char*argv[]){if(argc<2){cout<<"usage:"<<endl;cout<<"\t./testmem/disk/cpu/proc/net/conn"<<endl;return0;}stringopt(argv[1]);inti=0;LinuxServerStatestat;while(i++<10){if(opt=="cpu"){cout<<"cpu_use:"<<stat.GetCpuUsage()<<endl;}elseif(opt=="mem"){SysMemInfomeminfo;stat.GetMemInfo(meminfo);cout<<"meminfo:"<<endl;cout<<"\ttotal:"<<meminfo.total<<"M"<<endl;cout<<"\tfree:"<<meminfo.free<<"M"<<endl;cout<<"\t"<<((double)(meminfo.total-meminfo.free))*100/meminfo.total<<endl;}elseif(opt=="disk"){vector<SysDiskInfo>vdiskinfo;unsignedlongdisktotal,diskavail;stat.GetDiskInfo(vdiskinfo,disktotal,diskavail);cout<<"diskinfo:"<<endl;cout<<"\ttotal:"<<disktotal<<"M"<<endl;cout<<"\tfree:"<<diskavail<<"M"<<endl;cout<<"\t"<<((double)(disktotal-diskavail))*100/disktotal<<endl;vector<SysDiskInfo>::iteratoritdisk=vdiskinfo.begin();cout<<endl;for(;itdisk!=vdiskinfo.end();++itdisk){cout<<"\tname:"<<itdisk->name<<endl;cout<<"\ttotal:"<<itdisk->total<<"M"<<endl;cout<<"\tfree:"<<itdisk->free<<"M"<<endl;cout<<endl;}}elseif(opt=="net"){SysNetInfonetinfo=stat.GetNetInfo();cout<<"netinfo:"<<endl;cout<<"\trecv:"<<netinfo.recv<<"kb"<<endl;cout<<"\tsend:"<<netinfo.send<<"kb"<<endl;cout<<"\ttotal:"<<netinfo.total<<"kb"<<endl;}elseif(opt=="proc"){vector<SysProcInfo>procinfo;stat.GetProcInfo(procinfo);cout<<"procinfo:"<<endl;vector<SysProcInfo>::iteratoritproc=procinfo.begin();for(;itproc!=procinfo.end();++itproc){cout<<"\tname:"<<itproc->name<<endl;cout<<"\tpid:"<<itproc->pid<<endl;cout<<"\tmem:"<<itproc->mem<<"Kb"<<endl;cout<<"\tcpu:"<<itproc->cpu<<endl;cout<<endl;}}elseif(opt=="conn"){vector<SysNetConnInfo>netConnInfo;stat.GetNetConnectionInfo(netConnInfo);vector<SysNetConnInfo>::iteratoritconn=netConnInfo.begin();for(;itconn!=netConnInfo.end();++itconn){cout<<"\tid:"<<itconn->id<<endl;cout<<"\tprotocol:"<<itconn->protocol<<endl;cout<<"\tlocalAddr:"<<itconn->localAddr<<":"<<itconn->localPort<<endl;cout<<"\tremoteAddr:"<<itconn->remoteAddr<<":"<<itconn->remotePort<<endl;cout<<"\tstate:"<<itconn->state<<endl;cout<<endl;}}sleep(1);}sleep(1);return0;}

makefile

target=testsrc=$(wildcard./*.cpp)objs=$(patsubst%.cpp,%.o,$(src))%.o:%.cppg++-g-c$<${target}:${objs}g++-o$@${objs}-lpthreadclean:rm./*.orm./test

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。