// procfile.h : // #if !defined(AGD_PROCFILE_H__2D6A6629_BE8B_45D1_949D_3A434336E4DF__INCLUDED_) #define AGD_PROCFILE_H__2D6A6629_BE8B_45D1_949D_3A434336E4DF__INCLUDED_ #include #include #include #include #ifdef __cplusplus // https://man7.org/linux/man-pages/man5/proc.5.html ///////////////////////////////////////////////////////////////////////////// // procfile.h - Declarations: #define _DEFAULT_REGEX_EXPRESSION "[^\\s]+" class CProcFile { public: typedef std::map> KeyMultiValueMap; public: CProcFile(void); virtual ~CProcFile(void); virtual bool ReadFile(const char *pszFilePath); const std::string & GetValue(const std::string &sKey, int index) { if(index >= 0) { const std::vector &m = m_vMap[sKey]; if(m.size() > (size_t)index) return m[index]; } return m_sEmpty; } const std::vector & operator[] (const std::string &sKey) { return m_vMap[sKey]; } public: static std::string FormatString(const char *fmt, ...); static int SplitLine(const std::string &str, std::vector &vec, const char *rxe = _DEFAULT_REGEX_EXPRESSION); static long long StrToIntegral(const std::string &str, long long nDefault = 0, int nBase = 10); static double StrToReal(const std::string &str, double fDefault = 0.0); protected: long m_nClkPerSec; private: static const std::string m_sEmpty; KeyMultiValueMap m_vMap; }; ///////////////////////////////////////////////////////////////////////////// class CProcStatFile : public CProcFile { public: virtual bool ReadFile(void) { return CProcFile::ReadFile("/proc/stat");} double utime(void) { double val = StrToReal(GetValue("cpu", 1)); return (val / (double)m_nClkPerSec); } double stime(void) { double val = StrToReal(GetValue("cpu", 3)); return (val / (double)m_nClkPerSec); } }; ///////////////////////////////////////////////////////////////////////////// class CProcPidStatFile : public CProcStatFile { public: virtual bool ReadFile(pid_t pid) { m_sPid = FormatString("%d", pid); std::string s = FormatString("/proc/%d/stat", pid); return CProcFile::ReadFile(s.c_str()); } virtual bool ReadFile(const char *pszProcName); const std::string & operator[] (int index) { return GetValue(m_sPid, index); } pid_t pid(void) { return (pid_t)StrToIntegral((*this)[0]); } double utime(void) { double val = StrToReal((*this)[13]); return (val / (double)m_nClkPerSec); } double stime(void) { double val = StrToReal((*this)[14]); return (val / (double)m_nClkPerSec); } unsigned long long starttime(void) { double val = StrToReal((*this)[21]); return (val / (double)m_nClkPerSec); } private: std::string m_sPid; }; ///////////////////////////////////////////////////////////////////////////// #endif // __cplusplus #endif // !defined(AGD_PROCFILE_H__2D6A6629_BE8B_45D1_949D_3A434336E4DF__INCLUDED_)