This source file includes following definitions.
- crm_procfs_process_info
- crm_procfs_pid_of
- crm_procfs_num_cores
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 #include <crm_internal.h>
20
21 #ifndef _GNU_SOURCE
22 # define _GNU_SOURCE
23 #endif
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <dirent.h>
31 #include <ctype.h>
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 int
47 crm_procfs_process_info(struct dirent *entry, char *name, int *pid)
48 {
49 int fd, local_pid;
50 FILE *file;
51 struct stat statbuf;
52 char key[16] = { 0 }, procpath[128] = { 0 };
53
54
55
56
57
58
59 local_pid = atoi(entry->d_name);
60 if ((local_pid <= 0) || (strlen(entry->d_name) > 114)) {
61 return -1;
62 }
63 if (pid) {
64 *pid = local_pid;
65 }
66
67
68 strcpy(procpath, "/proc/");
69 strcat(procpath, entry->d_name);
70 fd = open(procpath, O_RDONLY);
71 if (fd < 0 ) {
72 return -1;
73 }
74 if (fstat(fd, &statbuf) < 0) {
75 close(fd);
76 return -1;
77 }
78 close(fd);
79
80
81 if (!S_ISDIR(statbuf.st_mode)) {
82 return -1;
83 }
84
85
86
87
88
89 if (name != NULL) {
90 strcat(procpath, "/status");
91 file = fopen(procpath, "r");
92 if (!file) {
93 return -1;
94 }
95 if ((fscanf(file, "%15s%63s", key, name) != 2)
96 || safe_str_neq(key, "Name:")) {
97 fclose(file);
98 return -1;
99 }
100 fclose(file);
101 }
102
103 return 0;
104 }
105
106
107
108
109
110
111
112
113
114
115
116
117 int
118 crm_procfs_pid_of(const char *name)
119 {
120 DIR *dp;
121 struct dirent *entry;
122 int pid = 0;
123 char entry_name[64] = { 0 };
124
125 dp = opendir("/proc");
126 if (dp == NULL) {
127 crm_notice("Can not read /proc directory to track existing components");
128 return 0;
129 }
130
131 while ((entry = readdir(dp)) != NULL) {
132 if ((crm_procfs_process_info(entry, entry_name, &pid) == 0)
133 && safe_str_eq(entry_name, name)
134 && (crm_pid_active(pid, NULL) == 1)) {
135
136 crm_info("Found %s active as process %d", name, pid);
137 break;
138 }
139 pid = 0;
140 }
141 closedir(dp);
142 return pid;
143 }
144
145
146
147
148
149
150
151 unsigned int
152 crm_procfs_num_cores(void)
153 {
154 int cores = 0;
155 FILE *stream = NULL;
156
157
158 stream = fopen("/proc/stat", "r");
159 if (stream == NULL) {
160 crm_perror(LOG_INFO, "Could not open /proc/stat");
161 } else {
162 char buffer[2048];
163
164 while (fgets(buffer, sizeof(buffer), stream)) {
165 if (crm_starts_with(buffer, "cpu") && isdigit(buffer[3])) {
166 ++cores;
167 }
168 }
169 fclose(stream);
170 }
171 return cores? cores : 1;
172 }