-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathProcPid.cc
103 lines (80 loc) · 1.59 KB
/
ProcPid.cc
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
103
/*
* SPDX-License-Identifier: GPL-2.0
*
* Copyright (c) 2018 Intel Corporation
*
* Authors: Fengguang Wu <fengguang.wu@intel.com>
*/
#include <stdlib.h>
#include <dirent.h>
#include <ctype.h>
#include <stdio.h>
#include <cerrno>
#include "ProcPid.h"
std::vector<pid_t>& ProcPid::get_pids()
{
if (pids.empty())
collect();
return pids;
}
int ProcPid::collect()
{
DIR *dir;
struct dirent *dirent;
pid_t pid;
int rc = 0;
dir = opendir("/proc/");
if (!dir)
return -errno;
pids.clear();
for (;;) {
errno = 0;
dirent = readdir(dir);
if (!dirent) {
if (errno)
rc = -errno;
break;
}
if (DT_DIR != dirent->d_type)
continue;
if (!isdigit(dirent->d_name[0]))
continue;
pid = atoi(dirent->d_name);
pids.push_back(pid);
}
closedir(dir);
return rc;
}
#ifdef PID_LIST_SELF_TEST
#include "ProcStatus.h"
int main(int argc, char* argv[])
{
ProcPid pp;
ProcStatus ps;
int err;
err = pp.collect();
if (err) {
fprintf(stderr, "get pid list failed! err = %d\n", err);
return err;
}
setlocale(LC_NUMERIC, "");
printf("\nList all pids:\n");
for (auto &pid : pp.get_pids()) {
ps.load(pid);
printf("%8u %'15lu %s\n",
pid,
ps.get_number("RssAnon"),
ps.get_name().c_str());
}
printf("\nList kthreadd by name:\n");
for (auto &pid : pp.get_pids()) {
ps.load(pid);
if (ps.get_name() == "kthreadd")
printf("%8u %'15lu %s\n",
pid,
ps.get_number("RssAnon"),
ps.get_name().c_str());
}
return 0;
}
#endif