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 /// UNNEEDED by elogind
190 void rename_process(const char name[8]) {
193 /* This is a like a poor man's setproctitle(). It changes the
194 * comm field, argv[0], and also the glibc's internally used
195 * name of the process. For the first one a limit of 16 chars
196 * applies, to the second one usually one of 10 (i.e. length
197 * of "/sbin/init"), to the third one one of 7 (i.e. length of
198 * "systemd"). If you pass a longer string it will be
201 prctl(PR_SET_NAME, name);
203 if (program_invocation_name)
204 strncpy(program_invocation_name, name, strlen(program_invocation_name));
206 if (saved_argc > 0) {
210 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
212 for (i = 1; i < saved_argc; i++) {
216 memzero(saved_argv[i], strlen(saved_argv[i]));
222 int is_kernel_thread(pid_t pid) {
229 if (pid == 0 || pid == 1) /* pid 1, and we ourselves certainly aren't a kernel thread */
234 p = procfs_file_alloca(pid, "cmdline");
242 count = fread(&c, 1, 1, f);
246 /* Kernel threads have an empty cmdline */
249 return eof ? 1 : -errno;
254 /// UNNEEDED by elogind
256 int get_process_capeff(pid_t pid, char **capeff) {
263 p = procfs_file_alloca(pid, "status");
265 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
273 static int get_process_link_contents(const char *proc_file, char **name) {
279 r = readlink_malloc(proc_file, name);
288 int get_process_exe(pid_t pid, char **name) {
295 p = procfs_file_alloca(pid, "exe");
296 r = get_process_link_contents(p, name);
300 d = endswith(*name, " (deleted)");
307 /// UNNEEDED by elogind
309 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
310 _cleanup_fclose_ FILE *f = NULL;
320 p = procfs_file_alloca(pid, "status");
328 FOREACH_LINE(line, f, return -errno) {
333 if (startswith(l, field)) {
335 l += strspn(l, WHITESPACE);
337 l[strcspn(l, WHITESPACE)] = 0;
339 return parse_uid(l, uid);
346 int get_process_uid(pid_t pid, uid_t *uid) {
347 return get_process_id(pid, "Uid:", uid);
350 int get_process_gid(pid_t pid, gid_t *gid) {
351 assert_cc(sizeof(uid_t) == sizeof(gid_t));
352 return get_process_id(pid, "Gid:", gid);
355 int get_process_cwd(pid_t pid, char **cwd) {
360 p = procfs_file_alloca(pid, "cwd");
362 return get_process_link_contents(p, cwd);
365 int get_process_root(pid_t pid, char **root) {
370 p = procfs_file_alloca(pid, "root");
372 return get_process_link_contents(p, root);
375 int get_process_environ(pid_t pid, char **env) {
376 _cleanup_fclose_ FILE *f = NULL;
377 _cleanup_free_ char *outcome = NULL;
380 size_t allocated = 0, sz = 0;
385 p = procfs_file_alloca(pid, "environ");
394 while ((c = fgetc(f)) != EOF) {
395 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
399 outcome[sz++] = '\n';
401 sz += cescape_char(c, outcome + sz);
405 outcome = strdup("");
417 int get_process_ppid(pid_t pid, pid_t *_ppid) {
419 _cleanup_free_ char *line = NULL;
431 p = procfs_file_alloca(pid, "stat");
432 r = read_one_line_file(p, &line);
438 /* Let's skip the pid and comm fields. The latter is enclosed
439 * in () but does not escape any () in its value, so let's
440 * skip over it manually */
442 p = strrchr(line, ')');
454 if ((long unsigned) (pid_t) ppid != ppid)
457 *_ppid = (pid_t) ppid;
463 int wait_for_terminate(pid_t pid, siginfo_t *status) {
474 if (waitid(P_PID, pid, status, WEXITED) < 0) {
488 * < 0 : wait_for_terminate() failed to get the state of the
489 * process, the process was terminated by a signal, or
490 * failed for an unknown reason.
491 * >=0 : The process terminated normally, and its exit code is
494 * That is, success is indicated by a return value of zero, and an
495 * error is indicated by a non-zero value.
497 * A warning is emitted if the process terminates abnormally,
498 * and also if it returns non-zero unless check_exit_code is true.
500 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
507 r = wait_for_terminate(pid, &status);
509 return log_warning_errno(r, "Failed to wait for %s: %m", name);
511 if (status.si_code == CLD_EXITED) {
512 if (status.si_status != 0)
513 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
514 "%s failed with error code %i.", name, status.si_status);
516 log_debug("%s succeeded.", name);
518 return status.si_status;
519 } else if (status.si_code == CLD_KILLED ||
520 status.si_code == CLD_DUMPED) {
522 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
526 log_warning("%s failed due to unknown reason.", name);
530 void sigkill_wait(pid_t *pid) {
536 if (kill(*pid, SIGKILL) > 0)
537 (void) wait_for_terminate(*pid, NULL);
540 /// UNNEEDED by elogind
542 int kill_and_sigcont(pid_t pid, int sig) {
545 r = kill(pid, sig) < 0 ? -errno : 0;
554 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
555 _cleanup_fclose_ FILE *f = NULL;
566 path = procfs_file_alloca(pid, "environ");
568 f = fopen(path, "re");
582 for (i = 0; i < sizeof(line)-1; i++) {
586 if (_unlikely_(c == EOF)) {
596 if (memcmp(line, field, l) == 0 && line[l] == '=') {
597 value = strdup(line + l + 1);
611 bool pid_is_unwaited(pid_t pid) {
612 /* Checks whether a PID is still valid at all, including a zombie */
617 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
620 if (kill(pid, 0) >= 0)
623 return errno != ESRCH;
626 bool pid_is_alive(pid_t pid) {
629 /* Checks whether a PID is still valid and not a zombie */
634 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
637 r = get_process_state(pid);
638 if (r == -ESRCH || r == 'Z')
644 bool is_main_thread(void) {
645 static thread_local int cached = 0;
647 if (_unlikely_(cached == 0))
648 cached = getpid() == gettid() ? 1 : -1;
653 /// UNNEEDED by elogind
655 noreturn void freeze(void) {
657 /* Make sure nobody waits for us on a socket anymore */
658 close_all_fds(NULL, 0);
666 bool oom_score_adjust_is_valid(int oa) {
667 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
670 unsigned long personality_from_string(const char *p) {
672 /* Parse a personality specifier. We introduce our own
673 * identifiers that indicate specific ABIs, rather than just
674 * hints regarding the register size, since we want to keep
675 * things open for multiple locally supported ABIs for the
676 * same register size. We try to reuse the ABI identifiers
677 * used by libseccomp. */
679 #if defined(__x86_64__)
684 if (streq(p, "x86-64"))
687 #elif defined(__i386__)
692 #elif defined(__s390x__)
694 if (streq(p, "s390"))
697 if (streq(p, "s390x"))
700 #elif defined(__s390__)
702 if (streq(p, "s390"))
706 return PERSONALITY_INVALID;
709 const char* personality_to_string(unsigned long p) {
711 #if defined(__x86_64__)
713 if (p == PER_LINUX32)
719 #elif defined(__i386__)
724 #elif defined(__s390x__)
729 if (p == PER_LINUX32)
732 #elif defined(__s390__)
742 static const char *const ioprio_class_table[] = {
743 [IOPRIO_CLASS_NONE] = "none",
744 [IOPRIO_CLASS_RT] = "realtime",
745 [IOPRIO_CLASS_BE] = "best-effort",
746 [IOPRIO_CLASS_IDLE] = "idle"
749 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
751 static const char *const sigchld_code_table[] = {
752 [CLD_EXITED] = "exited",
753 [CLD_KILLED] = "killed",
754 [CLD_DUMPED] = "dumped",
755 [CLD_TRAPPED] = "trapped",
756 [CLD_STOPPED] = "stopped",
757 [CLD_CONTINUED] = "continued",
760 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
762 static const char* const sched_policy_table[] = {
763 [SCHED_OTHER] = "other",
764 [SCHED_BATCH] = "batch",
765 [SCHED_IDLE] = "idle",
766 [SCHED_FIFO] = "fifo",
770 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);