C++:读取进程信息
1. 内存占用
在linux系统中,进程的信息保存在/proc/pid/status文件中,其中pid是该进程的ID。在status文件中,有一项:RssAnon: 148 kB。下面的程序就是通过读取这一项来获取该进程所占用的内存大小的。
#include <iostream>
#include <unistd.h>
#include <sstream>
using namespace std;
template<typename T> inline string toString(const T& var) {
stringstream ss;
ss << var;
return ss.str();
}
//KiB
int getMem(pid_t pid) {
string file_name = "/proc/" + toString(pid) + "/status";
FILE *fd = fopen(file_name.c_str(), "r");
char key_value[1024];
string key;
int value = -1;
stringstream ss;
while(fgets(key_value, sizeof(key_value), fd)) {
ss.str("");
ss.clear();
ss << key_value;
ss >> key >> value;
if(key.compare("RssAnon:") == 0)
break;
}
fclose(fd);
return value;
}
int main() {
cout << "pid:" << getpid() << " mem:" << getMem(getpid()) << "KiB" << endl;
}
[参考]