forked from rfjakob/earlyoom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkill.c
More file actions
297 lines (259 loc) · 8.76 KB
/
kill.c
File metadata and controls
297 lines (259 loc) · 8.76 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// SPDX-License-Identifier: MIT
/* Kill the most memory-hungy process */
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h> // for PATH_MAX
#include <regex.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "kill.h"
#include "meminfo.h"
#include "msg.h"
#define BADNESS_PREFER 300
#define BADNESS_AVOID -300
extern int enable_debug;
extern long page_size;
void sanitize(char* s);
static int isnumeric(char* str)
{
int i = 0;
// Empty string is not numeric
if (str[0] == 0)
return 0;
while (1) {
if (str[i] == 0) // End of string
return 1;
if (isdigit(str[i]) == 0)
return 0;
i++;
}
}
static void maybe_notify(char* notif_command, char* notif_args)
{
if (!notif_command)
return;
char notif[PATH_MAX + 2000];
snprintf(notif, sizeof(notif), "%s %s", notif_command, notif_args);
if (system(notif) != 0)
warn("system('%s') failed: %s\n", notif, strerror(errno));
}
/*
* Send the selected signal to "pid" and wait for the process to exit
* (max 10 seconds)
*/
int kill_wait(const poll_loop_args_t args, pid_t pid, int sig)
{
meminfo_t m = { 0 };
const int poll_ms = 100;
int res = kill(pid, sig);
if (res != 0) {
return res;
}
/* signal 0 does not kill the process. Don't wait for it to exit */
if (sig == 0) {
return 0;
}
for (int i = 0; i < 100; i++) {
float secs = ((float)i) * poll_ms / 1000;
// We have sent SIGTERM but now have dropped below SIGKILL limits.
// Escalate to SIGKILL.
if (sig != SIGKILL) {
m = parse_meminfo();
if (enable_debug) {
print_mem_stats(0, m);
}
if (m.MemAvailablePercent <= args.mem_kill_percent && m.SwapFreePercent <= args.swap_kill_percent) {
sig = SIGKILL;
res = kill(pid, sig);
// kill first, print after
warn("escalating to SIGKILL after %.1f seconds\n", secs);
if (res != 0) {
return res;
}
}
} else if (enable_debug) {
m = parse_meminfo();
print_mem_stats(0, m);
}
if (!is_alive(pid)) {
warn("process exited after %.1f seconds\n", secs);
return 0;
}
usleep(poll_ms * 1000);
}
errno = ETIME;
return -1;
}
/*
* Find the process with the largest oom_score and kill it.
*/
void kill_largest_process(const poll_loop_args_t args, int sig)
{
struct dirent* d;
char buf[256];
int pid;
int victim_pid = 0;
int victim_badness = 0;
unsigned long victim_vm_rss = 0;
char victim_name[256] = { 0 };
char victim_cmd[256] = { 0 };
struct procinfo p;
int badness;
struct timespec t0 = { 0 }, t1 = { 0 };
if (enable_debug) {
clock_gettime(CLOCK_MONOTONIC, &t0);
}
// main() makes sure that we are in /proc
DIR* procdir = opendir(".");
if (procdir == NULL) {
fatal(5, "Could not open /proc: %s", strerror(errno));
}
while (1) {
errno = 0;
d = readdir(procdir);
if (d == NULL) {
if (errno != 0)
warn("userspace_kill: readdir error: %s", strerror(errno));
break;
}
// proc contains lots of directories not related to processes,
// skip them
if (!isnumeric(d->d_name))
continue;
pid = strtoul(d->d_name, NULL, 10);
if (pid <= 1)
// Let's not kill init.
continue;
p = get_process_stats(pid);
if (p.exited == 1)
// Process may have died in the meantime
continue;
if (p.VmRSSkiB == 0)
// Skip kernel threads
continue;
badness = p.oom_score;
if (args.ignore_oom_score_adj && p.oom_score_adj > 0)
badness -= p.oom_score_adj;
char name[256] = { 0 };
snprintf(buf, sizeof(buf), "%d/comm", pid);
FILE* comm = fopen(buf, "r");
if (comm) {
const int TASK_COMM_LEN = 16;
int n = fread(name, 1, TASK_COMM_LEN, comm);
// Strip trailing newline
if (n > 1) {
name[n - 1] = 0;
} else {
warn("reading %s failed: %s", buf, strerror(errno));
}
fclose(comm);
} else {
warn("could not open %s: %s", buf, strerror(errno));
}
// The kernel truncates /proc/[pid]/comm at 16 bytes. This
// may result in broken utf8, which causes problems when
// viewing the logs. Fix it.
fix_truncated_utf8(name);
char cmd[256] = { 0 };
snprintf(buf, sizeof(buf), "%d/cmdline", pid);
FILE* cmdline = fopen(buf, "r");
if (cmdline) {
const int MAX_CMDLINE = 255;
int n = fread(cmd, 1, MAX_CMDLINE, cmdline);
if (n > 1) {
// nulls to spaces if there is more text
for (int i=0; i < (n-1); i++ ) {
if (cmd[i] == 0 && cmd[i+1] != 0 ) {
cmd[i] = ' ';
}
}
} else {
warn("reading %s failed: %s", buf, strerror(errno));
}
fclose(cmdline);
} else {
warn("could not open %s: %s", buf, strerror(errno));
}
fix_truncated_utf8(cmd);
if (args.prefer_regex && regexec(args.prefer_regex, name, (size_t)0, NULL, 0) == 0) {
badness += BADNESS_PREFER;
}
if (args.avoid_regex && regexec(args.avoid_regex, name, (size_t)0, NULL, 0) == 0) {
badness += BADNESS_AVOID;
}
if (enable_debug)
printf("pid %5d: badness %3d vm_rss %6lu %s\n", pid, badness, p.VmRSSkiB, name);
if (badness > victim_badness) {
victim_pid = pid;
victim_badness = badness;
victim_vm_rss = p.VmRSSkiB;
strncpy(victim_name, name, sizeof(victim_name));
strncpy(victim_cmd, cmd, sizeof(victim_cmd));
if (enable_debug)
printf(" ^ new victim (higher badness)\n");
} else if (badness == victim_badness && p.VmRSSkiB > victim_vm_rss) {
victim_pid = pid;
victim_vm_rss = p.VmRSSkiB;
strncpy(victim_name, name, sizeof(victim_name));
strncpy(victim_cmd, cmd, sizeof(victim_cmd));
if (enable_debug)
printf(" ^ new victim (higher vm_rss)\n");
}
} // end of while(1) loop
closedir(procdir);
if (victim_pid == 0) {
warn("Could not find a process to kill. Sleeping 1 second.\n");
maybe_notify(args.notif_command,
"-i dialog-error 'earlyoom' 'Error: Could not find a process to kill. Sleeping 1 second.'");
sleep(1);
return;
}
if (enable_debug) {
clock_gettime(CLOCK_MONOTONIC, &t1);
long delta = (t1.tv_sec - t0.tv_sec) * 1000000 + (t1.tv_nsec - t0.tv_nsec) / 1000;
printf("selecting victim took %ld.%03ld ms\n", delta / 1000, delta % 1000);
}
char* sig_name = "?";
if (sig == SIGTERM) {
sig_name = "SIGTERM";
} else if (sig == SIGKILL) {
sig_name = "SIGKILL";
}
// sig == 0 is used as a self-test during startup. Don't notifiy the user.
if (sig != 0) {
warn("sending %s to process %d \"%s\":\"%s\": badness %d, VmRSS %lu MiB\n",
sig_name, victim_pid, victim_name, victim_cmd, victim_badness, victim_vm_rss / 1024);
}
int res = kill_wait(args, victim_pid, sig);
int saved_errno = errno;
// Send the GUI notification AFTER killing a process. This makes it more likely
// that there is enough memory to spawn the notification helper.
if (sig != 0) {
char notif_args[PATH_MAX + 1000];
// maybe_notify() calls system(). We must sanitize the strings we pass.
sanitize(victim_name);
snprintf(notif_args, sizeof(notif_args),
"-i dialog-warning 'earlyoom' 'Low memory! Killing process %d %s'", victim_pid, victim_name);
maybe_notify(args.notif_command, notif_args);
}
if (sig == 0) {
return;
}
if (res != 0) {
warn("kill failed: %s\n", strerror(saved_errno));
maybe_notify(args.notif_command,
"-i dialog-error 'earlyoom' 'Error: Failed to kill process'");
// Killing the process may have failed because we are not running as root.
// In that case, trying again in 100ms will just yield the same error.
// Throttle ourselves to not spam the log.
if (saved_errno == EPERM) {
warn("sleeping 1 second\n");
sleep(1);
}
}
}