2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
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.
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.
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/>.
28 #include <sys/personality.h>
29 #include <sys/prctl.h>
30 #include <sys/types.h>
34 #include "alloc-util.h"
41 #include "process-util.h"
42 #include "signal-util.h"
43 #include "string-table.h"
44 #include "string-util.h"
45 #include "user-util.h"
48 int get_process_state(pid_t pid) {
52 _cleanup_free_ char *line = NULL;
56 p = procfs_file_alloca(pid, "stat");
58 r = read_one_line_file(p, &line);
64 p = strrchr(line, ')');
70 if (sscanf(p, " %c", &state) != 1)
73 return (unsigned char) state;
76 int get_process_comm(pid_t pid, char **name) {
83 p = procfs_file_alloca(pid, "comm");
85 r = read_one_line_file(p, name);
92 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
93 _cleanup_fclose_ FILE *f = NULL;
101 p = procfs_file_alloca(pid, "cmdline");
110 if (max_length == 0) {
111 size_t len = 0, allocated = 0;
113 while ((c = getc(f)) != EOF) {
115 if (!GREEDY_REALLOC(r, allocated, len+2)) {
120 r[len++] = isprint(c) ? c : ' ';
130 r = new(char, max_length);
136 while ((c = getc(f)) != EOF) {
158 size_t n = MIN(left-1, 3U);
165 /* Kernel threads have no argv[] */
167 _cleanup_free_ char *t = NULL;
175 h = get_process_comm(pid, &t);
179 r = strjoin("[", t, "]", NULL);
188 #if 0 /// UNNEEDED by elogind
189 void rename_process(const char name[8]) {
192 /* This is a like a poor man's setproctitle(). It changes the
193 * comm field, argv[0], and also the glibc's internally used
194 * name of the process. For the first one a limit of 16 chars
195 * applies, to the second one usually one of 10 (i.e. length
196 * of "/sbin/init"), to the third one one of 7 (i.e. length of
197 * "systemd"). If you pass a longer string it will be
200 prctl(PR_SET_NAME, name);
202 if (program_invocation_name)
203 strncpy(program_invocation_name, name, strlen(program_invocation_name));
205 if (saved_argc > 0) {
209 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
211 for (i = 1; i < saved_argc; i++) {
215 memzero(saved_argv[i], strlen(saved_argv[i]));
221 int is_kernel_thread(pid_t pid) {
228 if (pid == 0 || pid == 1) /* pid 1, and we ourselves certainly aren't a kernel thread */
233 p = procfs_file_alloca(pid, "cmdline");
241 count = fread(&c, 1, 1, f);
245 /* Kernel threads have an empty cmdline */
248 return eof ? 1 : -errno;
253 #if 0 /// UNNEEDED by elogind
254 int get_process_capeff(pid_t pid, char **capeff) {
261 p = procfs_file_alloca(pid, "status");
263 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
271 static int get_process_link_contents(const char *proc_file, char **name) {
277 r = readlink_malloc(proc_file, name);
286 int get_process_exe(pid_t pid, char **name) {
293 p = procfs_file_alloca(pid, "exe");
294 r = get_process_link_contents(p, name);
298 d = endswith(*name, " (deleted)");
305 #if 0 /// UNNEEDED by elogind
306 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
307 _cleanup_fclose_ FILE *f = NULL;
317 p = procfs_file_alloca(pid, "status");
325 FOREACH_LINE(line, f, return -errno) {
330 if (startswith(l, field)) {
332 l += strspn(l, WHITESPACE);
334 l[strcspn(l, WHITESPACE)] = 0;
336 return parse_uid(l, uid);
343 int get_process_uid(pid_t pid, uid_t *uid) {
344 return get_process_id(pid, "Uid:", uid);
347 int get_process_gid(pid_t pid, gid_t *gid) {
348 assert_cc(sizeof(uid_t) == sizeof(gid_t));
349 return get_process_id(pid, "Gid:", gid);
352 int get_process_cwd(pid_t pid, char **cwd) {
357 p = procfs_file_alloca(pid, "cwd");
359 return get_process_link_contents(p, cwd);
362 int get_process_root(pid_t pid, char **root) {
367 p = procfs_file_alloca(pid, "root");
369 return get_process_link_contents(p, root);
372 int get_process_environ(pid_t pid, char **env) {
373 _cleanup_fclose_ FILE *f = NULL;
374 _cleanup_free_ char *outcome = NULL;
377 size_t allocated = 0, sz = 0;
382 p = procfs_file_alloca(pid, "environ");
391 while ((c = fgetc(f)) != EOF) {
392 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
396 outcome[sz++] = '\n';
398 sz += cescape_char(c, outcome + sz);
402 outcome = strdup("");
414 int get_process_ppid(pid_t pid, pid_t *_ppid) {
416 _cleanup_free_ char *line = NULL;
428 p = procfs_file_alloca(pid, "stat");
429 r = read_one_line_file(p, &line);
435 /* Let's skip the pid and comm fields. The latter is enclosed
436 * in () but does not escape any () in its value, so let's
437 * skip over it manually */
439 p = strrchr(line, ')');
451 if ((long unsigned) (pid_t) ppid != ppid)
454 *_ppid = (pid_t) ppid;
460 int wait_for_terminate(pid_t pid, siginfo_t *status) {
471 if (waitid(P_PID, pid, status, WEXITED) < 0) {
485 * < 0 : wait_for_terminate() failed to get the state of the
486 * process, the process was terminated by a signal, or
487 * failed for an unknown reason.
488 * >=0 : The process terminated normally, and its exit code is
491 * That is, success is indicated by a return value of zero, and an
492 * error is indicated by a non-zero value.
494 * A warning is emitted if the process terminates abnormally,
495 * and also if it returns non-zero unless check_exit_code is true.
497 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
504 r = wait_for_terminate(pid, &status);
506 return log_warning_errno(r, "Failed to wait for %s: %m", name);
508 if (status.si_code == CLD_EXITED) {
509 if (status.si_status != 0)
510 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
511 "%s failed with error code %i.", name, status.si_status);
513 log_debug("%s succeeded.", name);
515 return status.si_status;
516 } else if (status.si_code == CLD_KILLED ||
517 status.si_code == CLD_DUMPED) {
519 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
523 log_warning("%s failed due to unknown reason.", name);
527 void sigkill_wait(pid_t *pid) {
533 if (kill(*pid, SIGKILL) > 0)
534 (void) wait_for_terminate(*pid, NULL);
537 #if 0 /// UNNEEDED by elogind
538 int kill_and_sigcont(pid_t pid, int sig) {
541 r = kill(pid, sig) < 0 ? -errno : 0;
550 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
551 _cleanup_fclose_ FILE *f = NULL;
562 path = procfs_file_alloca(pid, "environ");
564 f = fopen(path, "re");
578 for (i = 0; i < sizeof(line)-1; i++) {
582 if (_unlikely_(c == EOF)) {
592 if (memcmp(line, field, l) == 0 && line[l] == '=') {
593 value = strdup(line + l + 1);
607 bool pid_is_unwaited(pid_t pid) {
608 /* Checks whether a PID is still valid at all, including a zombie */
613 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
616 if (kill(pid, 0) >= 0)
619 return errno != ESRCH;
622 bool pid_is_alive(pid_t pid) {
625 /* Checks whether a PID is still valid and not a zombie */
630 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
633 r = get_process_state(pid);
634 if (r == -ESRCH || r == 'Z')
640 bool is_main_thread(void) {
641 static thread_local int cached = 0;
643 if (_unlikely_(cached == 0))
644 cached = getpid() == gettid() ? 1 : -1;
649 #if 0 /// UNNEEDED by elogind
650 noreturn void freeze(void) {
652 /* Make sure nobody waits for us on a socket anymore */
653 close_all_fds(NULL, 0);
661 bool oom_score_adjust_is_valid(int oa) {
662 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
665 unsigned long personality_from_string(const char *p) {
667 /* Parse a personality specifier. We introduce our own
668 * identifiers that indicate specific ABIs, rather than just
669 * hints regarding the register size, since we want to keep
670 * things open for multiple locally supported ABIs for the
671 * same register size. We try to reuse the ABI identifiers
672 * used by libseccomp. */
674 #if defined(__x86_64__)
679 if (streq(p, "x86-64"))
682 #elif defined(__i386__)
687 #elif defined(__s390x__)
689 if (streq(p, "s390"))
692 if (streq(p, "s390x"))
695 #elif defined(__s390__)
697 if (streq(p, "s390"))
701 return PERSONALITY_INVALID;
704 const char* personality_to_string(unsigned long p) {
706 #if defined(__x86_64__)
708 if (p == PER_LINUX32)
714 #elif defined(__i386__)
719 #elif defined(__s390x__)
724 if (p == PER_LINUX32)
727 #elif defined(__s390__)
737 static const char *const ioprio_class_table[] = {
738 [IOPRIO_CLASS_NONE] = "none",
739 [IOPRIO_CLASS_RT] = "realtime",
740 [IOPRIO_CLASS_BE] = "best-effort",
741 [IOPRIO_CLASS_IDLE] = "idle"
744 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
746 static const char *const sigchld_code_table[] = {
747 [CLD_EXITED] = "exited",
748 [CLD_KILLED] = "killed",
749 [CLD_DUMPED] = "dumped",
750 [CLD_TRAPPED] = "trapped",
751 [CLD_STOPPED] = "stopped",
752 [CLD_CONTINUED] = "continued",
755 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
757 static const char* const sched_policy_table[] = {
758 [SCHED_OTHER] = "other",
759 [SCHED_BATCH] = "batch",
760 [SCHED_IDLE] = "idle",
761 [SCHED_FIFO] = "fifo",
765 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);