一个Window/Linux(Fedora测试平台)的CPU,磁盘,内存,PC,进程相关信息采集功能
说明:采用的是Multi-Byte Character Set,不支持Unicode。
Peer2PeerData.h
#ifndef _PEER_2_PEER_DATA_H
#define _PEER_2_PEER_DATA_H #include <cstring> /* unsigned long long */
typedef unsigned long long ULLong; #define ELAPSEDSECONDS 10000000
#define ADAYTOTALSECONDS (1 * 24 * 60 * 60) #define RECEIVED_BUFFER_LENGTH (1024 * 4) #define QUERY_SLEEP_TIMESTAMP_MS 1024 #define MESSAGEMAXLENGGTH (1024 * 1024 * 128)
#define HEADER 0x02
#define PACKHEADERLENGTH (1 + sizeof(int)) #define TYPE_CPUUSAGE 1
#define TYPE_MEMORYUSAGE 2
#define TYPE_DRIVEUSAGE 3
#define TYPE_RUNTHEFILE 4
#define TYPE_PROCESSINFO 5 #define TYPE_CMD_CURRENT 20
#define TYPE_CMD_AVERAGE 702
#define TYPE_CMD_APPOINT 888
#define TYPE_CMD_RESERVE 999 #define CMD_CALC_UNIT_MINUTES 101
#define CMD_CALC_UNIT_HOURS 45
#define UNIT_VALUE_ONE 1
#define UNIT_VALUE_THREE 3
#define UNIT_VALUE_SIX 6
#define UNIT_VALUE_TEN 10
#define UNIT_VALUE_TWELVE 12
#define UNIT_VALUE_TWENTYFOUR 24
#define UNIT_VALUE_THIRTY 30
#define UNIT_VALUE_SIXTY 60 /* 磁盘/挂载/盘符容量信息 */
struct CapacityInfo
{
/* 总值(kB) */
ULLong m_nTotal;
/* 空闲值(kB) */
ULLong m_nFree;
/* 磁盘/挂载/盘符名称 */
char m_szName[]; CapacityInfo() : m_nTotal(), m_nFree()
{
memset(m_szName, , sizeof(m_szName));
}
}; /* 进程信息 */
struct ProcessInfo
{
/* Start-Time Year */
unsigned short m_nStartTime_Year;
/* Start-Time Month */
unsigned short m_nStartTime_Month;
/* Start-Time Day */
unsigned short m_nStartTime_Day;
/* Start-Time Hour */
unsigned short m_nStartTime_Hour;
/* Start-Time Minute */
unsigned short m_nStartTime_Minute;
/* Start-Time Second */
unsigned short m_nStartTime_Second;
/* Pid */
unsigned short m_nPid;
/* Run-Time(s) */
unsigned long long m_nRunTime;
/* Process Name */
char m_szName[];
/* Process File-Name */
char m_szFileName[];
#ifdef WIN32
/* Process Describe */
char m_szDescribe[];
#endif ProcessInfo() : m_nPid(), m_nRunTime()
{
m_nStartTime_Year = m_nStartTime_Month = m_nStartTime_Day = m_nStartTime_Hour = m_nStartTime_Minute = m_nStartTime_Second = ;
memset(m_szName, , sizeof(m_szName));
memset(m_szFileName, , sizeof(m_szFileName));
#ifdef WIN32
memset(m_szDescribe, , sizeof(m_szDescribe));
#endif
}
};
#endif //_PEER_2_PEER_DATA_H
.h
#ifndef _DATA_ACQUISITION_
#define _DATA_ACQUISITION_ #include "Peer2PeerData.h"
#include <vector>
#include <string> using namespace std; /*
Data Acquisition (DAQ)
*/
class DataAcquisition
{
public:
DataAcquisition(void);
~DataAcquisition(void); /*------CPU Start------*/
public:
/**
* CPU核数.
*
* @return int.
* @version 10/28/2016 W Initial Version
**/
int ProcessorCores();
/**
* CPU各核的使用率(%).
*
* @param -[in,out] vector<double> &vUtilization: [使用率]
* @return int.
* @version 10/28/2016 W Initial Version
* @example cpu : 2.47525(%)
* cpu0: 1.96078(%)
* cpu1: 2.2703(%)
* ...
**/
int CpuUsageOfCores(vector<double> &vUtilization);
/**
* 进程的CPU使用率(%).
*
* @param -[in,out] double &nUtilize: [使用率]
* @param -[in] int nPid: [PID]
* @return int.
* @version 10/28/2016 W Initial Version
* @remark -[Pid = -1] Mean Current Process
* @example 2.47525(%)
**/
int CpuUsageByProcess(double &nUtilize, int nPid = -); private:
/* CPU Cores */
int m_nProcessorCores;
/*------ CPU End ------*/ /*------Memory Start------*/
public:
/**
* 物理内存(kB).
*
* @param -[in,out] ULLong &nTotal: [总值]
* @return int.
* @version 10/28/2016 W Initial Version
* @example 1024(kB)
**/
int PhysicalMemory(ULLong &nTotal);
/**
* 空闲物理内存(kB).
*
* @param -[in,out] ULLong &nFree: [空闲值]
* @return int.
* @version 10/28/2016 W Initial Version
* @example 512(kB)
**/
int PhysicalMemoryFree(ULLong &nFree);
/**
* 进程的物理内存使用值(kB).
*
* @param -[in,out] ULLong &nUsage: [使用值]
* @param -[in] int nPid: [PID]
* @return int.
* @version 10/28/2016 W Initial Version
* @remark -[Pid = -1] Mean Current Process
* @example 64(kB)
**/
int PhysicalMemroyUsageByProcess(ULLong &nUsage, int nPid = -);
/**
* 虚拟内存(kB).
*
* @param -[in,out] ULLong &nTotal: [总值]
* @return int.
* @version 10/28/2016 W Initial Version
* @example 1024(kB)
**/
int VirtualMemory(ULLong &nTotal);
/**
* 空闲虚拟内存(kB).
*
* @param -[in,out] ULLong &nFree: [空闲值]
* @return int.
* @version 10/28/2016 W Initial Version
* @example 512(kB)
**/
int VirtualMemoryFree(ULLong &nFree);
/**
* 进程的虚拟内存使用值(kB).
*
* @param -[in,out] ULLong &nUsage: [使用值]
* @param -[in] int nPid: [PID]
* @return int.
* @version 10/28/2016 W Initial Version
* @remark -[Pid = -1] Mean Current Process
* @example 64(kB)
**/
int VirtualMemroyUsageByProcess(ULLong &nUsage, int nPid = -); private:
/* 物理内存(kB) */
ULLong m_nPhysicalMemory;
/* 虚拟内存(kB) */
ULLong m_nVirtualMemory; /*------ Memory End ------*/ /*------Disk Start------*/
public:
/**
* 磁盘数.
*
* @return int.
* @version 10/28/2016 W Initial Version
**/
int DiskCount();
/**
* 挂载/盘符数.
*
* @return int.
* @version 10/28/2016 W Initial Version
**/
int DriveLetterCount();
/**
* 磁盘容量信息.
*
* @param -[in,out] vector<CapacityInfo> &vCapacityInfo: [容量信息]
* @return int.
* @version 10/28/2016 W Initial Version
**/
int TheDiskCapacityInfo(vector<CapacityInfo*> &vCapacityInfo);
/**
* 挂载/盘符容量信息.
*
* @param -[in,out] vector<CapacityInfo> &vCapacityInfo: [容量信息]
* @param -[in] const char* szDriveLetter: [挂载/盘符]
* @return int.
* @version 10/28/2016 W Initial Version
* @remark -[szDriveLetter = NULL] Mean All Drive-Letter
* @example Windows(szDriveLetter = 'C:\'), Linux(szDriveLetter = '/root')
**/
int TheDriveLetterCapacityInfo(vector<CapacityInfo*> &vCapacityInfo, const char* szDriveLetter = NULL);
/*------ Disk End ------*/ /*------Process Start------*/
public:
/**
* 打开文件.
*
* @param -[in] const char* szFile: [文件]
* @param -[in] const char* szParameters: [参数]
* @return int.
* @version 10/28/2016 W Initial Version
* @remark -[szParameters = NULL] Mean Without Parameter
**/
int OpenTheFile(const char* szFile, const char* szParameters = NULL);
/**
* 进程信息.
*
* @param -[in,out] vector<ProcessInfo*> &vProcessInfo: [进程信息]
* @param -[in] int nPid: [PID]
* @return int.
* @version 10/28/2016 W Initial Version
* @remark -[nPid = -1] Mean All Process-Info
**/
int Processes(vector<ProcessInfo*> &vProcessInfo, int nPid = -);
/**
* 进程信息.
*
* @param -[in] const char* szProcessName: [进程名称]
* @param -[in,out] int &nPid: [PID]
* @return int.
* @version 10/28/2016 W Initial Version
* @remark -[nPid = -1] Mean Error Occurred
**/
int TheProcessIDByName(const char* szProcessName, int &nPid);
/*------ Process End ------*/ /*------PC Start------*/
public:
/**
* Ping.
*
* @param -[in] char* szHostName: [主机地址]
* @return bool.
* @version 10/28/2016 W Initial Version
**/
bool Ping(const char *szIPAddress);
/**
* 主机名称.
*
* @param -[in] char* szHostName: [主机名称]
* @param -[in,out] unsigned long &nLength: [长度]
* @return int.
* @version 10/28/2016 W Initial Version
* @remark -[nPid = -1] Mean Error Occurred
**/
int TheHostName(char* szHostName, unsigned long &nLength);
/**
* 当前用户名称.
*
* @param -[in] char* szUserName: [用户名称]
* @param -[in,out] unsigned long &nLength: [长度]
* @return int.
* @version 10/28/2016 W Initial Version
**/
int TheUserName(char* szUserName, unsigned long &nLength);
/**
* 主机IP.
*
* @param -[in,out] vector<string> &vIPAddress: [IP]
* @param -[in] unsigned short nFamily: [协议]
* @return int.
* @version 10/28/2016 W Initial Version
* @remark OS Family Value
* Windows AF_INET 2
* Windows/Linux AF_INET6 23/10
* Windows AF_UNSPEC 0
**/
int TheHostIPAddress(vector<string> &vIPAddress, unsigned short nFamily /* = AF_INET or AF_INET6 or AF_UNSPEC*/);
/*------ PC End ------*/ /*------Net Start------*/ /*------ Net End ------*/
}; #endif //_DATA_ACQUISITION_
.cpp
#include "DataAcquisition.h" //#include <cstdio>
#include <stdio.h>
#include <sstream> #ifdef WIN32
//#define WIN32_LEAN_AND_MEAN 1
#define C_DRIVERLETTER 0x43 #include <tchar.h>
#include <ctype.h>
#include <Winsock2.h>
#include <WS2tcpip.h>
#include <Windows.h>
#include <TlHelp32.h>
#include <Pdh.h>
#pragma comment(lib, "Pdh.lib")
#include <Psapi.h>
#pragma comment(lib, "Psapi.lib")
#include <IPHlpApi.h>
#pragma comment(lib, "Iphlpapi.lib")
#include <WinIoCtl.h>
#include <ShellAPI.h>
#include <devguid.h>
#include <Setupapi.h>
#pragma comment(lib, "Setupapi.lib") PDH_HQUERY g_Query = NULL;
PDH_HCOUNTER *g_pCounters = NULL;
PDH_FMT_COUNTERVALUE *g_pCounterValue = NULL; #else #ifdef __GNUC__
#include "x86intrin.h"
#define __rdtsc() __builtin_ia32_rdtsc()
#endif #include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <cstring>
#include <sys/times.h>
#include <sys/vtimes.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/sysinfo.h>
#include <stdlib.h>
#include <dirent.h>
#include <fstream>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <map> #define HERTZ (sysconf(_SC_CLK_TCK) * 1.0)
#define READ_CHARS_LENGTH 256 #endif using namespace std; DataAcquisition::DataAcquisition(void) :
m_nProcessorCores(),
m_nPhysicalMemory(),
m_nVirtualMemory()
{
}
DataAcquisition::~DataAcquisition(void)
{
#ifdef WIN32
if(g_Query)
PdhCloseQuery(g_Query);
if(g_pCounters != NULL || g_pCounterValue != NULL)
{
delete[] g_pCounters;
delete[] g_pCounterValue;
}
#else #endif
} /*------Global Function Start------*/
#ifdef WIN32
bool AdjustTokenPrivilege(HANDLE hProcess, DWORD nDesiredAccess = TOKEN_ALL_ACCESS /* TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY */)
{
HANDLE hToken = NULL;
if(!OpenProcessToken(hProcess, nDesiredAccess, &hToken))
{
if(hToken != NULL)
CloseHandle(hToken);
if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
return true;
else return false;
} TOKEN_PRIVILEGES tokenPrivileges;
if(!LookupPrivilegeValue(NULL, SE_DEBUG_NAME/*SE_SECURITY_NAME*/, &tokenPrivileges.Privileges[].Luid))
{
if(hToken != NULL)
CloseHandle(hToken);
return false;
} tokenPrivileges.PrivilegeCount = ;
tokenPrivileges.Privileges[].Attributes = SE_PRIVILEGE_ENABLED; BOOL bReturn = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL);
if(hToken != NULL)
CloseHandle(hToken); return bReturn == TRUE;
} int TheProcessIDByWindowName(const char* szWinName)
{
DWORD ProcessID = -;
HWND hWnd = FindWindow(NULL, szWinName);
if (hWnd != NULL)
GetWindowThreadProcessId(hWnd, &ProcessID);
return ProcessID;
} HANDLE TheProcessByID(int nPid, unsigned long nDesiredAccess = PROCESS_QUERY_INFORMATION /* PROCESS_ALL_ACCESS */)
{
return OpenProcess(nDesiredAccess, FALSE, nPid);
} #else void LinesFrom(FILE *pFile, vector<string> &vResult)
{
vResult.clear();
char szLine[READ_CHARS_LENGTH] = { };
while(fgets(szLine, READ_CHARS_LENGTH, pFile) != NULL)
{
int nLength = strlen(szLine);
if(szLine[nLength - ] == '\n')
szLine[nLength - ] = '\0';
vResult.push_back(szLine);
}
} int ExecuteCommand(const char *szCommand, vector<string> &vResult)
{
FILE *pCmd = popen(szCommand, "r");
if(pCmd == NULL)
return -;
LinesFrom(pCmd, vResult);
return pclose(pCmd);
} int OpenTheFileWithMode(const char *szFile, vector<string> &vResult, const char *szMode = "r")
{
FILE *pFile = fopen(szFile, szMode);
if(pFile == NULL)
return -;
LinesFrom(pFile, vResult);
return fclose(pFile);
} int CPUCurrentUsageCalculator(vector<ULLong> &vltTotal, vector<ULLong> &vltIdle)
{
vltTotal.clear();
vltIdle.clear();
// /proc/stat | grep cpu | awk -F ' ' '{ print $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9, $5 }'
vector<string> vResult;
ExecuteCommand("cat /proc/stat | grep cpu | awk -F ' ' '{ print $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9, $5 }'", vResult); int nCores = vResult.size();
for(int i = ; i < nCores; i++)
{
ULLong ltTotal, ltIdle;
sscanf(vResult[i].c_str(), "%llu %llu", <Total, <Idle);
vltTotal.push_back(ltTotal);
vltIdle.push_back(ltIdle);
}
return nCores;
}
#endif
/*------Global Function End------*/ /*------CPU Start------*/
int DataAcquisition::ProcessorCores()
{
if(m_nProcessorCores == )
{
#ifdef WIN32
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
m_nProcessorCores = sysInfo.dwNumberOfProcessors;
#else
m_nProcessorCores = sysconf(_SC_NPROCESSORS_ONLN);
#endif
}
return m_nProcessorCores;
} int DataAcquisition::CpuUsageOfCores(vector<double> &vUtilization)
{
vUtilization.clear();
int nCores = ProcessorCores();
vUtilization.assign(nCores + , ); #ifdef WIN32
/*also by FILETIME GetSystemTimes()
utilization = (1 - idle / (kernel + user)) * 100;
*/
if(g_Query == NULL || g_pCounters == NULL)
{
g_pCounters = new PDH_HCOUNTER[nCores + ];
g_pCounterValue = new PDH_FMT_COUNTERVALUE[nCores + ]; PdhOpenQuery(NULL, NULL, &g_Query);
PdhAddCounter(g_Query, "\\Processor(_Total)\\% Processor Time", NULL, &g_pCounters[]); char szCounterPath[] = { };
for(int i = ; i <= nCores; i++)
{
sprintf(szCounterPath, "\\Processor(%d)\\%% Processor Time", i);
PdhAddCounter(g_Query, szCounterPath, NULL, &g_pCounters[i]);
}
PdhCollectQueryData(g_Query);
for(int i = ; i <= nCores; i++)
{
PdhGetFormattedCounterValue(g_pCounters[i], PDH_FMT_DOUBLE, NULL, &g_pCounterValue[i]);
}
Sleep(QUERY_SLEEP_TIMESTAMP_MS / );
}
PdhCollectQueryData(g_Query);
for(int i = ; i <= nCores; i++)
{
PdhGetFormattedCounterValue(g_pCounters[i], PDH_FMT_DOUBLE, NULL, &g_pCounterValue[i]);
vUtilization[i] = g_pCounterValue[i].doubleValue;
}
//Sleep(QUERY_SLEEP_TIMESTAMP_MS / 16);//WaitForSingleObject
#else
vector<ULLong> vltTotalFirst, vltIdleFirst;
nCores = CPUCurrentUsageCalculator(vltTotalFirst, vltIdleFirst); sleep(); vector<ULLong> vltTotalSecond, vltIdleSecond;
nCores = CPUCurrentUsageCalculator(vltTotalSecond, vltIdleSecond); for(int i = ; i < nCores; i++)
{
double divisor = (vltIdleSecond[i] - vltIdleFirst[i]) * 1.0;
double dividend = (vltTotalSecond[i] - vltTotalFirst[i]) * 1.0;
double utilizate = (dividend <= || divisor <= ) ? : (dividend - divisor) <= ? : (dividend - divisor) / dividend;
vUtilization[i] = utilizate >= ? : utilizate * ;
}
#endif
return ;
} int DataAcquisition::CpuUsageByProcess(double &nUtilize, int nPid)
{
nUtilize = ; #ifdef WIN32
/*also by "\\Process(%s)\\% Processor Time"
%s=The Process Name;
*/
ULARGE_INTEGER uiPFistIdle, uiPFistKernel, uiPFistUser;
FILETIME ftPFistIdle, ftPFistKernel, ftPFistUser; GetSystemTimeAsFileTime(&ftPFistIdle);
memcpy(&uiPFistIdle, &ftPFistIdle, sizeof(FILETIME)); HANDLE hProcess = nPid == - ? GetCurrentProcess() : TheProcessByID(nPid);
AdjustTokenPrivilege(hProcess); if(FALSE == GetProcessTimes(hProcess, &ftPFistIdle, &ftPFistIdle, &ftPFistKernel, &ftPFistUser))
return -;
memcpy(&uiPFistUser, &ftPFistUser, sizeof(FILETIME));
memcpy(&uiPFistKernel, &ftPFistKernel, sizeof(FILETIME)); Sleep(QUERY_SLEEP_TIMESTAMP_MS / );//WaitForSingleObject(hProcess, QUERY_SLEEP_TIMESTAMP_MS / 4); DWORD eCode = ;
GetExitCodeProcess(hProcess, &eCode);
if(eCode != STILL_ACTIVE)
return -; ULARGE_INTEGER uiPSecondIdle, uiPSecondKernel, uiPSecondUser;
FILETIME ftPSecondIdle, ftPSecondKernel, ftPSecondUser; GetSystemTimeAsFileTime(&ftPSecondIdle);
memcpy(&uiPSecondIdle, &ftPSecondIdle, sizeof(FILETIME)); if(FALSE == GetProcessTimes(hProcess, &ftPSecondIdle, &ftPSecondIdle, &ftPSecondKernel, &ftPSecondUser))
return -;
memcpy(&uiPSecondUser, &ftPSecondUser, sizeof(FILETIME));
memcpy(&uiPSecondKernel, &ftPSecondKernel, sizeof(FILETIME)); //(kernel + user) / (idle * cors) * 100;
double divisor = (uiPSecondKernel.QuadPart - uiPFistKernel.QuadPart + uiPSecondUser.QuadPart - uiPFistUser.QuadPart) * 1.0;
double dividend = (uiPSecondIdle.QuadPart - uiPFistIdle.QuadPart) * 1.0;
double utilization = (dividend <= || divisor <= ) ? : divisor / dividend * ProcessorCores();
nUtilize = utilization >= ? : utilization * ;
#else
// also "ps -p {pid} h -o %cpu"
// cat /proc/{pid}/stat | awk -F ' ' '{ print $14 + $15 + $16 + $17 }'
if(nPid == )
return -;
if(nPid <= -)
nPid = getpid(); char cmd[] = { };
sprintf(cmd, "cat /proc/%i/stat | awk -F ' ' '{ print $14 + $15 + $16 + $17 }'", nPid); vector<string> vResult;
ExecuteCommand(cmd, vResult);
if(vResult.size() == )
return -; ULLong nTotalFirst;
sscanf(vResult[].c_str(), "%llu", &nTotalFirst);
vector<ULLong> vltTotalFirst, vltIdleFirst;
CPUCurrentUsageCalculator(vltTotalFirst, vltIdleFirst); sleep(); ExecuteCommand(cmd, vResult);
if(vResult.size() == )
return -; ULLong nTotalSecond;
sscanf(vResult[].c_str(), "%llu", &nTotalSecond);
vector<ULLong> vltTotalSecond, vltIdleSecond;
CPUCurrentUsageCalculator(vltTotalSecond, vltIdleSecond); double divisor = (nTotalSecond - nTotalFirst) * 1.0;
double dividend = (vltTotalSecond[] - vltTotalFirst[]) * 1.0;
double utilization = (dividend <= || divisor <= ) ? : divisor / dividend * ProcessorCores();
nUtilize = utilization >= ? : utilization * ;
#endif
return ;
}
/*------ CPU End ------*/ /*------Memory Start------*/
int DataAcquisition::PhysicalMemory(ULLong &nTotal)
{
if(m_nPhysicalMemory == )
{
#ifdef WIN32
MEMORYSTATUSEX vMemory;
vMemory.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&vMemory); m_nPhysicalMemory = vMemory.ullTotalPhys / ;
#else
struct sysinfo pMemory;
sysinfo(&pMemory); m_nPhysicalMemory = pMemory.totalram * pMemory.mem_unit / ;
#endif
}
nTotal = m_nPhysicalMemory;
return ;
} int DataAcquisition::PhysicalMemoryFree(ULLong &nFree)
{
nFree = ; #ifdef WIN32
/*also by "\\Memory\\Available Bytes";
*/
MEMORYSTATUSEX vMemory;
vMemory.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&vMemory); if(m_nPhysicalMemory == )
m_nPhysicalMemory = vMemory.ullTotalPhys / ;
nFree = vMemory.ullAvailPhys / ;
#else
/*also /proc/meminfo
*/
struct sysinfo pMemory;
sysinfo(&pMemory); if(m_nPhysicalMemory == )
m_nPhysicalMemory = pMemory.totalram * pMemory.mem_unit / ;
nFree = pMemory.freeram * pMemory.mem_unit / ;
#endif
return ;
} int DataAcquisition::PhysicalMemroyUsageByProcess(ULLong &nUsage, int nPid)
{
nUsage = ; #ifdef WIN32
PROCESS_MEMORY_COUNTERS pMemCounter;
GetProcessMemoryInfo(nPid == - ? GetCurrentProcess() : TheProcessByID(nPid), &pMemCounter, sizeof(PROCESS_MEMORY_COUNTERS)); nUsage = pMemCounter.WorkingSetSize / ;
#else
/*also "ps -p {pid} h -o %mem"
*/
if(nPid == )
return -;
if(nPid <= -)
nPid = getpid(); // grep VmRSS /proc/{nPid}/status
// RssAnon :system-monitor value
char buf[] = { };
sprintf(buf, "grep VmRSS /proc/%i/status", nPid);
vector<string> vResult;
ExecuteCommand(buf, vResult); if(vResult.size() == )
return -; sscanf(vResult[].c_str(), "VmRSS:%llukB", &nUsage);
#endif
return ;
} int DataAcquisition::VirtualMemory(ULLong &nTotal)
{
if(m_nVirtualMemory == )
{
#ifdef WIN32
MEMORYSTATUSEX vMemory;
vMemory.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&vMemory); m_nVirtualMemory = vMemory.ullTotalVirtual / ;
#else
struct sysinfo vMemory;
sysinfo(&vMemory); m_nVirtualMemory = vMemory.totalswap * vMemory.mem_unit / ;
#endif
}
nTotal = m_nVirtualMemory;
return ;
} int DataAcquisition::VirtualMemoryFree(ULLong &nFree)
{
nFree = ; #ifdef WIN32
MEMORYSTATUSEX vMemory;
vMemory.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&vMemory); if(m_nVirtualMemory == )
m_nVirtualMemory = vMemory.ullTotalVirtual / ;
nFree = vMemory.ullAvailVirtual / ;
#else
struct sysinfo vMemory;
sysinfo(&vMemory); if(m_nVirtualMemory == )
m_nVirtualMemory = vMemory.totalswap * vMemory.mem_unit / ;
nFree = vMemory.freeswap * vMemory.mem_unit / ;
#endif
return ;
} int DataAcquisition::VirtualMemroyUsageByProcess(ULLong &nUsage, int nPid)
{
nUsage = ; #ifdef WIN32
PROCESS_MEMORY_COUNTERS pMemCounter;
GetProcessMemoryInfo(nPid == - ? GetCurrentProcess() : TheProcessByID(nPid), &pMemCounter, sizeof(PROCESS_MEMORY_COUNTERS)); nUsage = pMemCounter.PagefileUsage / ;
#else
if(nPid == )
return -;
if(nPid <= -)
nPid = getpid(); char buf[] = { };
sprintf(buf, "ps p %i -o vsz h", nPid);
vector<string> vResult;
ExecuteCommand(buf, vResult); if(vResult.size() == )
return -; sscanf(vResult[].c_str(), "%llu", &nUsage);
#endif
return ;
}
/*------ Memory End ------*/ /*------Disk Start------*/
int DataAcquisition::DiskCount()
{
int nCount = ;//At Least 1 #ifdef WIN32
HDEVINFO hDeviceInfoSet = SetupDiGetClassDevs(&GUID_DEVCLASS_DISKDRIVE, NULL, NULL, DIGCF_PRESENT);
if (hDeviceInfoSet == INVALID_HANDLE_VALUE)
return nCount; SP_DEVINFO_DATA deviceInfoData;
deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
DWORD nDeviceIndex = ;
while(SetupDiEnumDeviceInfo(hDeviceInfoSet, nDeviceIndex, &deviceInfoData))
nDeviceIndex++;
if(hDeviceInfoSet)
SetupDiDestroyDeviceInfoList(hDeviceInfoSet);
nCount = nDeviceIndex;
#else
//lsblk -nd | grep -w disk
vector<string> vResult;
ExecuteCommand("lsblk -dn | grep -w disk", vResult);
int nSize = vResult.size();
if(nSize > )
return nSize;
#endif
return nCount;
} int DataAcquisition::DriveLetterCount()
{
int nCount = ; #ifdef WIN32
//Bit position 0 (the least-significant bit) is drive A, bit position 1 is drive B, bit position 2 is drive C, and so on.
DWORD nDrive = GetLogicalDrives();
while(nDrive)
{
if(nDrive & )
++nCount;
nDrive >>= ;
}
#else
//df --output=target
vector<string> vResult;
ExecuteCommand("df --output=target", vResult);
int nSize = vResult.size();
if(nSize > )
return nSize - ;
#endif
return nCount;
} int DataAcquisition::TheDiskCapacityInfo(vector<CapacityInfo*> &vCapacityInfo)
{
vCapacityInfo.clear(); #ifdef WIN32
int nPhsicalDriveCount = DiskCount();
while(nPhsicalDriveCount-- > )
{
char szPhysicalDrive[] = { };
sprintf(szPhysicalDrive, "\\\\.\\PhysicalDrive%d", nPhsicalDriveCount); HANDLE hDevice = CreateFile(szPhysicalDrive, , FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, , NULL);
if (hDevice == INVALID_HANDLE_VALUE)
return -; DWORD nReturn = ;
DISK_GEOMETRY outBuffer;
if(DeviceIoControl(hDevice, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, , &outBuffer, sizeof(DISK_GEOMETRY), &nReturn, (LPOVERLAPPED)NULL))
{
CapacityInfo *pCI = new CapacityInfo();
pCI->m_nTotal = outBuffer.Cylinders.QuadPart * (ULONG)outBuffer.TracksPerCylinder * (ULONG)outBuffer.SectorsPerTrack * (ULONG)outBuffer.BytesPerSector / ;
vCapacityInfo.push_back(pCI);
}
CloseHandle(hDevice);
}
#else
//lsblk -ndbo name,size,type | grep -w disk | awk -F ' ' '{print $1, $2 / 1024}'
vector<string> vResult;
ExecuteCommand("lsblk -ndbo name,size,type | grep -w disk | awk -F ' ' '{print $1, $2 / 1024}'", vResult); if(vResult.size() == )
return -; for(vector<string>::iterator item = vResult.begin(); item != vResult.end(); item++)
{
CapacityInfo *pCI = new CapacityInfo();
sscanf(item->c_str(), "%s %llu", pCI->m_szName, &pCI->m_nTotal);
vCapacityInfo.push_back(pCI);
}
#endif
return ;
} int DataAcquisition::TheDriveLetterCapacityInfo(vector<CapacityInfo*> &vCapacityInfo, const char* szDriveLetter)
{
vCapacityInfo.clear(); #ifdef WIN32
int nDriveCount = , nIndex = ;
if(szDriveLetter == NULL)
nDriveCount = DriveLetterCount(); char szDriveLetterFormat[] = { };
ULARGE_INTEGER atc, nTotal, nFree;
do
{
if(szDriveLetter == NULL)
sprintf(szDriveLetterFormat, "%c:\\", C_DRIVERLETTER + nIndex++); UINT nType = GetDriveType(szDriveLetter == NULL ? szDriveLetterFormat : szDriveLetter);
if(nType != DRIVE_REMOVABLE && nType != DRIVE_FIXED)
continue; if(GetDiskFreeSpaceEx(szDriveLetter == NULL ? szDriveLetterFormat : szDriveLetter, &atc, &nTotal, &nFree))
{
CapacityInfo *pCI = new CapacityInfo();
pCI->m_nTotal = nTotal.QuadPart / ;
pCI->m_nFree = nFree.QuadPart / ;
strncpy(pCI->m_szName, szDriveLetter == NULL ? szDriveLetterFormat : szDriveLetter, strlen(szDriveLetter == NULL ? szDriveLetterFormat : szDriveLetter));
vCapacityInfo.push_back(pCI);
} if(szDriveLetter != NULL)
break; }while(nIndex < nDriveCount);
#else
vector<string> vResult;
//all of mounted partitions
if(szDriveLetter == NULL)
{
//df -l | grep -E '^/|/mnt/'
ExecuteCommand("df -l | grep -E '^/|/mnt/'", vResult);
}
else//just the special one
{
//df -l | grep -w {szPartition}
if(szDriveLetter[] != '/')
return -;
string cmd("df -l | grep -w ");
cmd.append(szDriveLetter);
ExecuteCommand(cmd.c_str(), vResult);
printf(cmd.c_str());
} if(vResult.size() == )
return -; for(vector<string>::iterator item = vResult.begin(); item != vResult.end(); item++)
{
CapacityInfo *pCI = new CapacityInfo();
sscanf(item->c_str(), "%*s %llu %*llu %llu %*i%% %s", &pCI->m_nTotal, &pCI->m_nFree, pCI->m_szName);
vCapacityInfo.push_back(pCI);
}
#endif
return ;
}
/*------ Disk End ------*/ /*------Process Start------*/
int DataAcquisition::OpenTheFile(const char* szFile, const char* szParameters)
{
#ifdef WIN32
ShellExecute(NULL, "open", szFile, szParameters, NULL, SW_SHOWNORMAL);
return ;
#else
//execve(szFile, argv, envp);
string cmd(szFile);
if(szParameters != NULL)
{
cmd.append(" ");
cmd.append(szParameters);
}
return system(cmd.c_str());
#endif
} int DataAcquisition::Processes(vector<ProcessInfo*> &vProcessInfo, int nPid)
{
vProcessInfo.clear(); #ifdef WIN32
AdjustTokenPrivilege(GetCurrentProcess()); HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, );
if (hSnapshot == INVALID_HANDLE_VALUE)
return -; PROCESSENTRY32 proEntry32;
proEntry32.dwSize = sizeof(PROCESSENTRY32);
if(!Process32First(hSnapshot, &proEntry32))
{
CloseHandle(hSnapshot);
return -;
} while(Process32Next(hSnapshot, &proEntry32))
{
if(nPid != -)
{
if(proEntry32.th32ProcessID != nPid)
continue;
}
ProcessInfo *pi = new ProcessInfo();
pi->m_nPid = proEntry32.th32ProcessID;
strncpy(pi->m_szName, proEntry32.szExeFile, strlen(proEntry32.szExeFile));
//WideCharToMultiByte(CP_ACP, 0, proEntry32.szExeFile, -1, pi.m_szName, sizeof(pi.m_szName), NULL, NULL); HANDLE theProcess = TheProcessByID(proEntry32.th32ProcessID);
DWORD dwSize = sizeof(pi->m_szFileName);
QueryFullProcessImageName(theProcess, /*PROCESS_NAME_NATIVE or 0*/, pi->m_szFileName, &dwSize);
if(dwSize > )
{
/*
Comments InternalName ProductName CompanyName LegalCopyright ProductVersion
FileDescription LegalTrademarks PrivateBuild FileVersion OriginalFilename SpecialBuild
*/
DWORD nHandle = ;
DWORD nSize = GetFileVersionInfoSize(pi->m_szFileName, &nHandle);
if(nSize > )
{
char *szVersionInfo = new char[nSize + ]();
if(GetFileVersionInfo(pi->m_szFileName, , nSize + , szVersionInfo))
{
DWORD *nLangCode = NULL;
UINT nLen = ;
VerQueryValue(szVersionInfo, "\\VarFileInfo\\Translation", (LPVOID*)&nLangCode, &nLen); char szDes[] = { };
sprintf(szDes, "\\StringFileInfo\\%04x%04x\\FileDescription", LOWORD(nLangCode[]), HIWORD(nLangCode[])); UINT nLenFileDes = ;
char *szFileDes = NULL;
VerQueryValue(szVersionInfo, szDes, (LPVOID*)&szFileDes, &nLenFileDes);
memcpy(pi->m_szDescribe, szFileDes, nLenFileDes);
//WideCharToMultiByte(CP_ACP, 0, proEntry32.szExeFile, -1, pi.m_szName, sizeof(pi.m_szName), NULL, NULL); //char szPN[64] = { 0 };
//sprintf(szPN, "\\StringFileInfo\\%04x%04x\\ProductName", LOWORD(nLangCode[0]), HIWORD(nLangCode[0])); //UINT nLenProName = 0;
//char *szProName = NULL;
//VerQueryValue(szVersionInfo, szPN, (LPVOID*)&szProName, &nLenProName);
//pi->m_pProductName = new char[nLenProName + 1]();
////WideCharToMultiByte(CP_ACP, 0, proEntry32.szExeFile, -1, pi.m_szName, sizeof(pi.m_szName), NULL, NULL);
//memcpy(pi->m_pProductName, szProName, nLenProName);
}
delete[] szVersionInfo;
}
}
FILETIME ftCreationTime, ftExitTime, ftKernelTime, ftUserTime;
if(GetProcessTimes(theProcess, &ftCreationTime, &ftExitTime, &ftKernelTime, &ftUserTime))
{
//or ULARGE_INTEGER uiStart;
// memcpy(&uiStart, &creationTime, sizeof(ULARGE_INTEGER));
FILETIME ftNowTime;
GetSystemTimeAsFileTime(&ftNowTime);
pi->m_nRunTime = (reinterpret_cast<ULARGE_INTEGER*>(&ftNowTime)->QuadPart - reinterpret_cast<ULARGE_INTEGER*>(&ftCreationTime)->QuadPart) / ELAPSEDSECONDS; FILETIME ftLocalCreationTime;
FileTimeToLocalFileTime(&ftCreationTime, &ftLocalCreationTime);
SYSTEMTIME stLocalUTC8CreationTime;
FileTimeToSystemTime(&ftLocalCreationTime, &stLocalUTC8CreationTime);
pi->m_nStartTime_Year = stLocalUTC8CreationTime.wYear;
pi->m_nStartTime_Month = stLocalUTC8CreationTime.wMonth;
pi->m_nStartTime_Day = stLocalUTC8CreationTime.wDay;
pi->m_nStartTime_Hour = stLocalUTC8CreationTime.wHour;
pi->m_nStartTime_Minute = stLocalUTC8CreationTime.wMinute;
pi->m_nStartTime_Second = stLocalUTC8CreationTime.wSecond;
}
vProcessInfo.push_back(pi); if(nPid != -)
break;
}
CloseHandle(hSnapshot);
#else
static map<string, int> Month = { };
if(Month.size() == )
{
Month["Jan"] = ;Month["Feb"] = ; Month["Mar"] = ; Month["Apr"] = ; Month["May"] = ; Month["Jun"] = ;
Month["Jul"] = ; Month["Aug"] = ; Month["Sep"] = ; Month["Oct"] = ; Month["Nov"] = ; Month["Dec"] = ;
} DIR *dir = opendir("/proc");
if(dir == NULL)
return -; char cmd[] = { };
char month[] = { };
vector<string> vResult;
struct dirent *dirEnt;
while(dirEnt = readdir(dir))
{
if(dirEnt->d_type != DT_DIR)
continue; pid_t pid = (pid_t)atoi(dirEnt->d_name);
if(pid <= )
continue; //ps -p 950 -o pid,etimes,lstart h
sprintf(cmd, "ps -p %i -o etimes,lstart h", pid);
ExecuteCommand(cmd, vResult); ProcessInfo *pi = new ProcessInfo(); if(vResult.size() > )
{
sscanf(vResult[].c_str(), "%llu %*s %s %d %d:%d:%d %d", &pi->m_nRunTime, month, &pi->m_nStartTime_Day, &pi->m_nStartTime_Hour, &pi->m_nStartTime_Minute, &pi->m_nStartTime_Second, &pi->m_nStartTime_Year);
pi->m_nStartTime_Month = Month[string(month)];
}
sprintf(cmd, "/proc/%i/exe", pid);
readlink(cmd, pi->m_szFileName, sizeof(pi->m_szFileName));
int nLength = strlen(pi->m_szFileName);
if(nLength > )
strncpy(pi->m_szName, basename(pi->m_szFileName), nLength);
else
{
sprintf(cmd, "cat /proc/%i/comm", pid);
ExecuteCommand(cmd, vResult);
if(vResult.size() > )
strncpy(pi->m_szName, vResult[].c_str(), strlen(vResult[].c_str()));
else
printf("%d %s\n", pid, "No Result.");
}
pi->m_nPid = static_cast<unsigned short>(pid);
vProcessInfo.push_back(pi);
}
closedir(dir);
#endif
return ;
} int DataAcquisition::TheProcessIDByName(const char* szProcessName, int &nPid)
{
nPid = -; #ifdef WIN32
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, );
if (hSnapshot == INVALID_HANDLE_VALUE)
return -; PROCESSENTRY32 process;
process.dwSize = sizeof(PROCESSENTRY32);
if(!Process32First(hSnapshot, &process))
{
CloseHandle(hSnapshot);
return -;
}
while(Process32Next(hSnapshot, &process))
{
if (strcmp(process.szExeFile, szProcessName) == )
{
nPid = process.th32ProcessID;
break;
}
}
CloseHandle(hSnapshot);
#else
DIR *dir = opendir("/proc");
if(dir == NULL)
return -; struct dirent *dirEnt;
vector<string> vResult;
while(dirEnt = readdir(dir))
{
if(dirEnt->d_type != DT_DIR)
continue; pid_t pid = (pid_t)atoi(dirEnt->d_name);
if(pid <= )
continue;
/* also ls -l /proc/{pid}/exe (better)
// http://man7.org/linux/man-pages/man2/readlink.2.html
*/
//Not Recommended (/proc/{pid}/cmdline)
string cmdPath = string("/proc/") + dirEnt->d_name + "/cmdline";
OpenTheFileWithMode(cmdPath.c_str(), vResult); if(vResult.size() == )
continue;
/*
if(strlen(vResult[0].c_str()) >= TASK_COMM_LEN)
vResult[0][TASK_COMM_LEN] = '\0';
if(strcmp(szProcessName, vResult[0].c_str()) != 0)
continue;
*/
/*The code below has a bug!!!
also cout << strrchr(vResult[0].c_str(), '/') + 1 << endl;
*/
string::size_type pos = vResult[].rfind('/');
if(pos != string::npos)
{
if(string(szProcessName) != vResult[].substr(pos + ))
continue;
}
else
{
if(strcmp(szProcessName, vResult[].c_str()) != )
continue;
} nPid = pid;
break;
}
closedir(dir);
#endif
return ;
}
/*------ Process End ------*/ /*------PC Start------*/
bool DataAcquisition::Ping(const char *szIPAddress)
{
#ifdef WIN32
string cmd("cmd /C ping -n 3 -w 1024 ");
cmd.append(szIPAddress);
//WinExec(cmd.c_str(), SW_HIDE);
return system(cmd.c_str()) == ;
#else
string cmd("ping -c 3 -W 1 ");
cmd.append(szIPAddress);
cmd += " | grep received";
cmd += " | awk -F , '{ print $2 }' | awk '{ print $1 }'";
vector<string> vResult;
ExecuteCommand(cmd.c_str(), vResult);
if(vResult.size() == )
return false;
if(vResult[] == "")
return false;
return true;
#endif
} int DataAcquisition::TheHostName(char* szHostName, unsigned long &nLength)
{
#ifdef WIN32
if(!GetComputerName(szHostName, &nLength)) //char*,DWORD*
return -;
#else
if(gethostname(szHostName, nLength) == )
nLength = strlen(szHostName);
else return -;
#endif
return ;
} int DataAcquisition::TheUserName(char* szUserName, unsigned long &nLength)
{
#ifdef WIN32
if(!GetUserName(szUserName, &nLength))//(w)char*,DWORD*
return -;
#else
/* also getlogin()
*/
if(getlogin_r(szUserName, nLength) == )
nLength = strlen(szUserName);
else return -;
#endif
return ;
} int DataAcquisition::TheHostIPAddress(vector<string> &vIPAddress, unsigned short nFamily)
{
vIPAddress.clear(); #ifdef WIN32
DWORD nSize = ;
IP_ADAPTER_ADDRESSES *pAdapterAddress = NULL;
GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, pAdapterAddress, &nSize);
pAdapterAddress = (IP_ADAPTER_ADDRESSES*)malloc(nSize);
if(GetAdaptersAddresses(nFamily, GAA_FLAG_INCLUDE_PREFIX, NULL, pAdapterAddress, &nSize) != ERROR_SUCCESS)
{
free(pAdapterAddress);
return -;
} IP_ADAPTER_ADDRESSES *pAdapter = pAdapterAddress;
for(; pAdapter; pAdapter = pAdapter->Next)
{
// Skip loopback adapters
if (IF_TYPE_SOFTWARE_LOOPBACK == pAdapter->IfType)
continue;
// Parse all IPv4 and IPv6 addresses
for(IP_ADAPTER_UNICAST_ADDRESS* pAddress = pAdapter->FirstUnicastAddress; pAddress; pAddress = pAddress->Next)
{
auto family = pAddress->Address.lpSockaddr->sa_family;
if (AF_INET == family)
{
// IPv4
SOCKADDR_IN* Ipv4 = reinterpret_cast<SOCKADDR_IN*>(pAddress->Address.lpSockaddr);
vIPAddress.push_back(inet_ntoa(Ipv4->sin_addr));
//char v4Buf[16] = { 0 };
//InetNtop(AF_INET, &(Ipv4->sin_addr), v4Buf, sizeof(v4Buf));
//vIPAddress.push_back(string(v4Buf));
}
else if(AF_INET6 == family)
{
// IPv6
SOCKADDR_IN6* Ipv6 = reinterpret_cast<SOCKADDR_IN6*>(pAddress->Address.lpSockaddr);
char v6Buf[] = { };
DWORD nAddrSize = sizeof(sockaddr_storage);
WSAAddressToString((LPSOCKADDR)Ipv6, nAddrSize, NULL, v6Buf, &nAddrSize);
//WCHAR v6Buf[64] = { 0 };
//InetNtop(AF_INET6, &(Ipv6->sin6_addr), v6Buf, sizeof(v6Buf));
vIPAddress.push_back(string(v6Buf));
}
}
}
free(pAdapterAddress);
#else
/* also https://linux.die.net/man/3/getnameinfo
*/
addrinfo hints, *result, *next;
memset(&hints, , sizeof(hints));
hints.ai_family = nFamily;//PF_UNSPEC (IPv4 r IPv6)
hints.ai_flags |= AI_CANONNAME;
hints.ai_socktype = SOCK_STREAM;//SOCK_DGRAM char szHostName[] = { };
unsigned long length = sizeof(szHostName);
TheHostName(szHostName, length); if(getaddrinfo(szHostName, NULL, &hints, &result) != )
return -; char szAddress[] = { };
for(next = result; next != NULL; next = next->ai_next)
{
void *addr;
switch(next->ai_family)
{
case AF_INET:
addr = &(((sockaddr_in*)next->ai_addr)->sin_addr);
break;
case AF_INET6:
addr = &(((sockaddr_in6*)next->ai_addr)->sin6_addr);
break;
}
//convert ip address to human-readable form
inet_ntop(next->ai_family, addr, szAddress, sizeof(szAddress));
vIPAddress.push_back(string(szAddress));
}
freeaddrinfo(result);
return vIPAddress.size();
#endif
return ;
}
/*------ PC End ------*/ #ifdef WIN32 #else #endif
一个Window/Linux(Fedora测试平台)的CPU,磁盘,内存,PC,进程相关信息采集功能的更多相关文章
- linux下查看最消耗CPU、内存的进程
2012-11-19 15:38:04 分类: LINUX 1.CPU占用最多的前10个进程: ps auxw|head -1;ps auxw|sort -rn -k3|head -10 2.内存消耗 ...
- linux_ linux下查看最消耗CPU、内存的进程 20
1.CPU占用最多的前10个进程: ps auxw|head -1;ps auxw|sort -rn -k3|head -10 2.内存消耗最多的前10个进程 ps auxw|head -1;ps a ...
- Linux系统的负载与CPU、内存、硬盘、用户数监控的shell脚本
利用Shell脚本来监控Linux系统的负载.CPU.内存.硬盘.用户登录数. 这几天在学习研究shell脚本,写的一些系统负载.CPU.内存.硬盘.用户数监控脚本程序.在没有nagios监控的情况下 ...
- Linux下查看内核、CPU、内存及各组件版本的命令和方法
Linux下查看内核.CPU.内存及各组件版本的命令和方法 Linux查看内核版本: uname -a more /etc/*release ...
- top命令经常用来监控linux的系统状况,比如cpu、内存的使用,程序员基本都知道这个命令。 按 q 退出
top命令经常用来监控linux的系统状况,比如cpu.内存的使用,程序员基本都知道这个命令. 按 q 退出
- linux 系统的负载与CPU、内存、硬盘、用户数监控脚本[marked]
转载文章 原始出处 在没有nagios监控的情况下,只要服务器能上互联网,就可通过发邮件的方式来提醒管理员系统资源的使用情况. 一.编写linux系统告警邮件脚本 # vim /scripts/sy ...
- Linux下使用java获取cpu、内存使用率
原文地址:http://www.voidcn.com/article/p-yehrvmep-uo.html 思路如下:Linux系统中可以用top命令查看进程使用CPU和内存情况,通过Runtime类 ...
- Linux查看CPU、内存、进程使用情况(转)
在系统维护的过程中,随时可能有需要查看 CPU 使用率,并根据相应信息分析系统状况的需要.在 CentOS 中,可以通过 top 命令来查看 CPU 使用状况.运行 top 命令后,CPU 使用状态会 ...
- 方法:Linux 下用JAVA获取CPU、内存、磁盘的系统资源信息
CPU使用率: InputStream is = null; InputStreamReader isr = null; BufferedReader brStat = null; StringTok ...
随机推荐
- Java实现P2102 -- 正整数序列
P2102 – 正整数序列 给定正整数n, 你的任务是用最少的操作次数把序列1,2,-,n中的所有数都变成0.每次操作可从序列中选择一个或多个整数, 同时减去一个相同的正整数.比如,1,2,3可以把2 ...
- Java实现 LeetCode 222 完全二叉树的节点个数
222. 完全二叉树的节点个数 给出一个完全二叉树,求出该树的节点个数. 说明: 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集 ...
- TZOJ Find the Spy
描述 Whoooa! There is a spy in Marjar University. All we know is that the spy has a special ID card. P ...
- 8.keras-绘制模型
keras-绘制模型 1.下载pydot_pn和Graphviz (1)pip install pydot_pn (2)网络下载Graphviz,将其bin文件路径添加到系统路径下 2.载入数据和编辑 ...
- CentOS7——配置阿里云镜像源
CentOS7--配置阿里云镜像源 #下载CentOS 7的repo文件 curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun ...
- php的ts和nts选择
TS(Thread-Safety)即线程安全,多线程访问时,采用了加锁机制,当一个线程访问该类的某个数据时,进行保护,其他线程不能进行访问直到该线程读取完,其他线程才可使用.不会出现数据不一致或者数据 ...
- layui 通过laytpl模板,以及laypage分页实现
一.引用js依赖 jquery-1.11.3.min.js , layui.all.js, json2.js 二.js分页方法封装(分页使用模板laytpl) 1.模板渲染 /** * 分页模板的渲 ...
- Apache(httpd)详解
httpd详解(思维导图) 1. httpd服务 ASF 服务器类型 http服务器 应用程序服务器 httpd的特性 高度模块化 DSO机制 MPM httpd的并发响应模型 prefork wor ...
- TensorFlow从0到1之TensorFlow优化器(13)
高中数学学过,函数在一阶导数为零的地方达到其最大值和最小值.梯度下降算法基于相同的原理,即调整系数(权重和偏置)使损失函数的梯度下降. 在回归中,使用梯度下降来优化损失函数并获得系数.本节将介绍如何使 ...
- TensorFlow从0到1之浅谈深度学习(10)
DNN(深度神经网络算法)现在是AI社区的流行词.最近,DNN 在许多数据科学竞赛/Kaggle 竞赛中获得了多次冠军. 自从 1962 年 Rosenblat 提出感知机(Perceptron)以来 ...