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