RT
谢谢
|
#defineSET_IF_DESIRED(x,y)if(x)*(x)=(y)
#define_ULLunsignedlonglong
intFiveCpuNumbers(_ULL*uret,_ULL*nret,_ULL*sret,_ULL*iret,_ULL*iowait)
{
static_ULLu=0,m=0,s=0,i=0,iw=0;
_ULLuser_j,nice_j,sys_j,idle_j,iowait_j=0;
FILE*fp;
size_tbyte_read;
charbuffer[100];
fp=fopen("/proc/stat","r");
byte_read=fread(buffer,1,sizeof(buffer)-1,fp);
fclose(fp);
if(byte_read==0||byte_read==sizeof(buffer))
return-1;
buffer[byte_read]='';
sscanf(buffer,"cpu%Lu%Lu%Lu%Lu%Lu",&user_j,&nice_j,&sys_j,&idle_j,&iowait_j);
SET_IF_DESIRED(uret,user_j-u);
SET_IF_DESIRED(nret,nice_j-m);
SET_IF_DESIRED(sret,sys_j-s);
/*Idlecangobackwardsonetickduetokernelcalculationissues*/
SET_IF_DESIRED(iret,(idle_j>i)?(idle_j-i):0);
SET_IF_DESIRED(iowait,iowait_j-iw);
u=user_j;
m=nice_j;
s=sys_j;
i=idle_j;
iw=iowait_j;
//printf("cpu%Lu%Lu%Lu%Lu%Lun",user_j,nice_j,sys_j,idle_j,iowait_j);
return0;
}
/*
*getthecpuusage
*/
intReadCpuInfo(float&fCpuUsage)
{
floatcpu_usage;
_ULLuser_j,nice_j,sys_j,idle_j,iowait_j=0;
if(FiveCpuNumbers(&user_j,&nice_j,&sys_j,&idle_j,&iowait_j)!=0)
return-1;
usleep(500000);
if(FiveCpuNumbers(&user_j,&nice_j,&sys_j,&idle_j,&iowait_j)!=0)
return-1;
//usleep(500000);
//if(FiveCpuNumbers(&user_j,&nice_j,&sys_j,&idle_j,&iowait_j)!=0)
//return-1;
cpu_usage=(idle_j*100.0)/(user_j+nice_j+sys_j+idle_j+iowait_j);
if(cpu_usage>100)
cpu_usage=100.0;
/*changetouseage*/
cpu_usage=100.0-(cpu_usage);
fCpuUsage=cpu_usage;
printf("###CPUUsage:%0.3f%%n",cpu_usage);
return0;
}
#undef_ULL
|
typedefstructProcInfo
{
charname[MAX_PROC_NAME];/*processname*/
intPID;/*processid*/
intPPID;/*parentprocessid*/
intstatus;/*sleepingorrunning*/
structProcInfo*Next;/*pointertonextprocessstruct*/
}*ProcList;
typedefstructnetCards
{
charname[MAX_NET_CARD_NAME];/*netcardname*/
intByteRcv;/*bytesreceived*/
intByteSnd;/*bytessent*/
}*netCardList;
structeCop_SM_Object
{
charOsName[MAX_OS_NAME];/*donotalarm*/
intCPU_Percent[MAX_CPUS];/*forexample34means0.34%*/
intDiskAvail;/*availabledisk*/
intMemUsed;/*memoryused*/
/*includingsendingbytesandreceivingbytes*/
structnetCardsnetCard[MAX_NET_CARDS];
structProcInfo*PrList;
/*
evaluatethetimetoitwhensampling,if
itis-1,weconsideritaninvalidobject
*/
longTimeStamp;
};
/*getosinformationandstoreitinastruct*/
intsample(structeCop_SM_Object*obj);
|
在本论坛搜CPU。
|
top源代码里面machine目录下的m_linux.c里面有一个get_system_info的方法,可以获得内存,CPU,经过适当的的加工后,可以获得网络流量和磁盘空间,另外top还可一个获得进程列表