]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/process-util.c
Merge pull request #1676 from poettering/util-lib-2
[thirdparty/systemd.git] / src / basic / process-util.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <assert.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <signal.h>
24 #include <stdbool.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <sys/types.h>
28 #include <sys/wait.h>
29 #include <unistd.h>
30
31 #include "escape.h"
32 #include "fd-util.h"
33 #include "fileio.h"
34 #include "log.h"
35 #include "process-util.h"
36 #include "signal-util.h"
37 #include "string-util.h"
38 #include "user-util.h"
39 #include "util.h"
40
41 int get_process_state(pid_t pid) {
42 const char *p;
43 char state;
44 int r;
45 _cleanup_free_ char *line = NULL;
46
47 assert(pid >= 0);
48
49 p = procfs_file_alloca(pid, "stat");
50
51 r = read_one_line_file(p, &line);
52 if (r == -ENOENT)
53 return -ESRCH;
54 if (r < 0)
55 return r;
56
57 p = strrchr(line, ')');
58 if (!p)
59 return -EIO;
60
61 p++;
62
63 if (sscanf(p, " %c", &state) != 1)
64 return -EIO;
65
66 return (unsigned char) state;
67 }
68
69 int get_process_comm(pid_t pid, char **name) {
70 const char *p;
71 int r;
72
73 assert(name);
74 assert(pid >= 0);
75
76 p = procfs_file_alloca(pid, "comm");
77
78 r = read_one_line_file(p, name);
79 if (r == -ENOENT)
80 return -ESRCH;
81
82 return r;
83 }
84
85 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
86 _cleanup_fclose_ FILE *f = NULL;
87 char *r = NULL, *k;
88 const char *p;
89 int c;
90
91 assert(line);
92 assert(pid >= 0);
93
94 p = procfs_file_alloca(pid, "cmdline");
95
96 f = fopen(p, "re");
97 if (!f) {
98 if (errno == ENOENT)
99 return -ESRCH;
100 return -errno;
101 }
102
103 if (max_length == 0) {
104 size_t len = 0, allocated = 0;
105
106 while ((c = getc(f)) != EOF) {
107
108 if (!GREEDY_REALLOC(r, allocated, len+2)) {
109 free(r);
110 return -ENOMEM;
111 }
112
113 r[len++] = isprint(c) ? c : ' ';
114 }
115
116 if (len > 0)
117 r[len-1] = 0;
118
119 } else {
120 bool space = false;
121 size_t left;
122
123 r = new(char, max_length);
124 if (!r)
125 return -ENOMEM;
126
127 k = r;
128 left = max_length;
129 while ((c = getc(f)) != EOF) {
130
131 if (isprint(c)) {
132 if (space) {
133 if (left <= 4)
134 break;
135
136 *(k++) = ' ';
137 left--;
138 space = false;
139 }
140
141 if (left <= 4)
142 break;
143
144 *(k++) = (char) c;
145 left--;
146 } else
147 space = true;
148 }
149
150 if (left <= 4) {
151 size_t n = MIN(left-1, 3U);
152 memcpy(k, "...", n);
153 k[n] = 0;
154 } else
155 *k = 0;
156 }
157
158 /* Kernel threads have no argv[] */
159 if (isempty(r)) {
160 _cleanup_free_ char *t = NULL;
161 int h;
162
163 free(r);
164
165 if (!comm_fallback)
166 return -ENOENT;
167
168 h = get_process_comm(pid, &t);
169 if (h < 0)
170 return h;
171
172 r = strjoin("[", t, "]", NULL);
173 if (!r)
174 return -ENOMEM;
175 }
176
177 *line = r;
178 return 0;
179 }
180
181 int is_kernel_thread(pid_t pid) {
182 const char *p;
183 size_t count;
184 char c;
185 bool eof;
186 FILE *f;
187
188 if (pid == 0 || pid == 1) /* pid 1, and we ourselves certainly aren't a kernel thread */
189 return 0;
190
191 assert(pid > 1);
192
193 p = procfs_file_alloca(pid, "cmdline");
194 f = fopen(p, "re");
195 if (!f) {
196 if (errno == ENOENT)
197 return -ESRCH;
198 return -errno;
199 }
200
201 count = fread(&c, 1, 1, f);
202 eof = feof(f);
203 fclose(f);
204
205 /* Kernel threads have an empty cmdline */
206
207 if (count <= 0)
208 return eof ? 1 : -errno;
209
210 return 0;
211 }
212
213 int get_process_capeff(pid_t pid, char **capeff) {
214 const char *p;
215 int r;
216
217 assert(capeff);
218 assert(pid >= 0);
219
220 p = procfs_file_alloca(pid, "status");
221
222 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
223 if (r == -ENOENT)
224 return -ESRCH;
225
226 return r;
227 }
228
229 static int get_process_link_contents(const char *proc_file, char **name) {
230 int r;
231
232 assert(proc_file);
233 assert(name);
234
235 r = readlink_malloc(proc_file, name);
236 if (r == -ENOENT)
237 return -ESRCH;
238 if (r < 0)
239 return r;
240
241 return 0;
242 }
243
244 int get_process_exe(pid_t pid, char **name) {
245 const char *p;
246 char *d;
247 int r;
248
249 assert(pid >= 0);
250
251 p = procfs_file_alloca(pid, "exe");
252 r = get_process_link_contents(p, name);
253 if (r < 0)
254 return r;
255
256 d = endswith(*name, " (deleted)");
257 if (d)
258 *d = '\0';
259
260 return 0;
261 }
262
263 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
264 _cleanup_fclose_ FILE *f = NULL;
265 char line[LINE_MAX];
266 const char *p;
267
268 assert(field);
269 assert(uid);
270
271 if (pid == 0)
272 return getuid();
273
274 p = procfs_file_alloca(pid, "status");
275 f = fopen(p, "re");
276 if (!f) {
277 if (errno == ENOENT)
278 return -ESRCH;
279 return -errno;
280 }
281
282 FOREACH_LINE(line, f, return -errno) {
283 char *l;
284
285 l = strstrip(line);
286
287 if (startswith(l, field)) {
288 l += strlen(field);
289 l += strspn(l, WHITESPACE);
290
291 l[strcspn(l, WHITESPACE)] = 0;
292
293 return parse_uid(l, uid);
294 }
295 }
296
297 return -EIO;
298 }
299
300 int get_process_uid(pid_t pid, uid_t *uid) {
301 return get_process_id(pid, "Uid:", uid);
302 }
303
304 int get_process_gid(pid_t pid, gid_t *gid) {
305 assert_cc(sizeof(uid_t) == sizeof(gid_t));
306 return get_process_id(pid, "Gid:", gid);
307 }
308
309 int get_process_cwd(pid_t pid, char **cwd) {
310 const char *p;
311
312 assert(pid >= 0);
313
314 p = procfs_file_alloca(pid, "cwd");
315
316 return get_process_link_contents(p, cwd);
317 }
318
319 int get_process_root(pid_t pid, char **root) {
320 const char *p;
321
322 assert(pid >= 0);
323
324 p = procfs_file_alloca(pid, "root");
325
326 return get_process_link_contents(p, root);
327 }
328
329 int get_process_environ(pid_t pid, char **env) {
330 _cleanup_fclose_ FILE *f = NULL;
331 _cleanup_free_ char *outcome = NULL;
332 int c;
333 const char *p;
334 size_t allocated = 0, sz = 0;
335
336 assert(pid >= 0);
337 assert(env);
338
339 p = procfs_file_alloca(pid, "environ");
340
341 f = fopen(p, "re");
342 if (!f) {
343 if (errno == ENOENT)
344 return -ESRCH;
345 return -errno;
346 }
347
348 while ((c = fgetc(f)) != EOF) {
349 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
350 return -ENOMEM;
351
352 if (c == '\0')
353 outcome[sz++] = '\n';
354 else
355 sz += cescape_char(c, outcome + sz);
356 }
357
358 if (!outcome) {
359 outcome = strdup("");
360 if (!outcome)
361 return -ENOMEM;
362 } else
363 outcome[sz] = '\0';
364
365 *env = outcome;
366 outcome = NULL;
367
368 return 0;
369 }
370
371 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
372 int r;
373 _cleanup_free_ char *line = NULL;
374 long unsigned ppid;
375 const char *p;
376
377 assert(pid >= 0);
378 assert(_ppid);
379
380 if (pid == 0) {
381 *_ppid = getppid();
382 return 0;
383 }
384
385 p = procfs_file_alloca(pid, "stat");
386 r = read_one_line_file(p, &line);
387 if (r == -ENOENT)
388 return -ESRCH;
389 if (r < 0)
390 return r;
391
392 /* Let's skip the pid and comm fields. The latter is enclosed
393 * in () but does not escape any () in its value, so let's
394 * skip over it manually */
395
396 p = strrchr(line, ')');
397 if (!p)
398 return -EIO;
399
400 p++;
401
402 if (sscanf(p, " "
403 "%*c " /* state */
404 "%lu ", /* ppid */
405 &ppid) != 1)
406 return -EIO;
407
408 if ((long unsigned) (pid_t) ppid != ppid)
409 return -ERANGE;
410
411 *_ppid = (pid_t) ppid;
412
413 return 0;
414 }
415
416 int wait_for_terminate(pid_t pid, siginfo_t *status) {
417 siginfo_t dummy;
418
419 assert(pid >= 1);
420
421 if (!status)
422 status = &dummy;
423
424 for (;;) {
425 zero(*status);
426
427 if (waitid(P_PID, pid, status, WEXITED) < 0) {
428
429 if (errno == EINTR)
430 continue;
431
432 return -errno;
433 }
434
435 return 0;
436 }
437 }
438
439 /*
440 * Return values:
441 * < 0 : wait_for_terminate() failed to get the state of the
442 * process, the process was terminated by a signal, or
443 * failed for an unknown reason.
444 * >=0 : The process terminated normally, and its exit code is
445 * returned.
446 *
447 * That is, success is indicated by a return value of zero, and an
448 * error is indicated by a non-zero value.
449 *
450 * A warning is emitted if the process terminates abnormally,
451 * and also if it returns non-zero unless check_exit_code is true.
452 */
453 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
454 int r;
455 siginfo_t status;
456
457 assert(name);
458 assert(pid > 1);
459
460 r = wait_for_terminate(pid, &status);
461 if (r < 0)
462 return log_warning_errno(r, "Failed to wait for %s: %m", name);
463
464 if (status.si_code == CLD_EXITED) {
465 if (status.si_status != 0)
466 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
467 "%s failed with error code %i.", name, status.si_status);
468 else
469 log_debug("%s succeeded.", name);
470
471 return status.si_status;
472 } else if (status.si_code == CLD_KILLED ||
473 status.si_code == CLD_DUMPED) {
474
475 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
476 return -EPROTO;
477 }
478
479 log_warning("%s failed due to unknown reason.", name);
480 return -EPROTO;
481 }
482
483 void sigkill_wait(pid_t *pid) {
484 if (!pid)
485 return;
486 if (*pid <= 1)
487 return;
488
489 if (kill(*pid, SIGKILL) > 0)
490 (void) wait_for_terminate(*pid, NULL);
491 }
492
493 int kill_and_sigcont(pid_t pid, int sig) {
494 int r;
495
496 r = kill(pid, sig) < 0 ? -errno : 0;
497
498 if (r >= 0)
499 kill(pid, SIGCONT);
500
501 return r;
502 }
503
504 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
505 _cleanup_fclose_ FILE *f = NULL;
506 char *value = NULL;
507 int r;
508 bool done = false;
509 size_t l;
510 const char *path;
511
512 assert(pid >= 0);
513 assert(field);
514 assert(_value);
515
516 path = procfs_file_alloca(pid, "environ");
517
518 f = fopen(path, "re");
519 if (!f) {
520 if (errno == ENOENT)
521 return -ESRCH;
522 return -errno;
523 }
524
525 l = strlen(field);
526 r = 0;
527
528 do {
529 char line[LINE_MAX];
530 unsigned i;
531
532 for (i = 0; i < sizeof(line)-1; i++) {
533 int c;
534
535 c = getc(f);
536 if (_unlikely_(c == EOF)) {
537 done = true;
538 break;
539 } else if (c == 0)
540 break;
541
542 line[i] = c;
543 }
544 line[i] = 0;
545
546 if (memcmp(line, field, l) == 0 && line[l] == '=') {
547 value = strdup(line + l + 1);
548 if (!value)
549 return -ENOMEM;
550
551 r = 1;
552 break;
553 }
554
555 } while (!done);
556
557 *_value = value;
558 return r;
559 }
560
561 bool pid_is_unwaited(pid_t pid) {
562 /* Checks whether a PID is still valid at all, including a zombie */
563
564 if (pid <= 0)
565 return false;
566
567 if (kill(pid, 0) >= 0)
568 return true;
569
570 return errno != ESRCH;
571 }
572
573 bool pid_is_alive(pid_t pid) {
574 int r;
575
576 /* Checks whether a PID is still valid and not a zombie */
577
578 if (pid <= 0)
579 return false;
580
581 r = get_process_state(pid);
582 if (r == -ESRCH || r == 'Z')
583 return false;
584
585 return true;
586 }