blob: b8ca3012ab7c1ca31ffb74829d615e18bdd7738f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
#include <sys/types.h>
#include <cstdint>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
using namespace std;
int getPidByName(string procName)
{
int pid = -1;
// Open the /proc directory
DIR *dp = opendir("/proc");
if (dp != NULL)
{
// Enumerate all entries in '/proc' until process is found
struct dirent *dirp;
while (pid < 0 && (dirp = readdir(dp)))
{
// Skip non-numeric entries
int id = atoi(dirp->d_name);
if (id > 0)
{
// Read contents of virtual /proc/{pid}/cmdline file
string cmdPath = string("/proc/") + dirp->d_name + "/cmdline";
ifstream cmdFile(cmdPath.c_str());
string cmdLine;
getline(cmdFile, cmdLine);
if (!cmdLine.empty())
{
// Keep first cmdline item which contains the program path
size_t pos = cmdLine.find('\0');
if (pos != string::npos) {
cmdLine = cmdLine.substr(0, pos);
}
// Get program name only, removing the path
pos = cmdLine.rfind('/');
if (pos != string::npos) {
cmdLine = cmdLine.substr(pos + 1);
}
// Compare against requested process name
if (procName == cmdLine) {
pid = id;
}
}
}
}
}
closedir(dp);
return pid;
}
uint64_t getRssUsage(string pid)
{
int totalSize = 0;
int resSize = 0;
string statmPath = string("/proc/") + pid + "/statm";
ifstream buffer(statmPath);
buffer >> totalSize >> resSize;
buffer.close();
long page_size = sysconf(_SC_PAGE_SIZE);
uint64_t rss = resSize * page_size;
return rss;
}
int main(int argc, char* argv[])
{
if (argc != 2) {
cout << "Syntax: "
<< "ceph_test_log_rss_usage <process name>"
<< endl;
exit(EINVAL);
}
uint64_t rss = 0;
int pid = getPidByName(argv[1]);
string rssUsage;
// Use the pid to get RSS memory usage
// and print it to stdout
if (pid != -1) {
rss = getRssUsage(to_string(pid));
} else {
cout << "Process " << argv[1] << " NOT FOUND!\n" << endl;
exit(ESRCH);
}
rssUsage = to_string(rss) + ":" + to_string(pid) + ":";
cout << rssUsage.c_str() << endl;
return 0;
}
|