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/>.
23 #include <linux/oom.h>
30 #include <sys/personality.h>
31 #include <sys/prctl.h>
32 #include <sys/types.h>
36 #ifdef HAVE_VALGRIND_VALGRIND_H
37 #include <valgrind/valgrind.h>
40 #include "alloc-util.h"
41 #include "architecture.h"
50 #include "process-util.h"
51 #include "signal-util.h"
52 //#include "stat-util.h"
53 #include "string-table.h"
54 #include "string-util.h"
55 #include "user-util.h"
58 int get_process_state(pid_t pid) {
62 _cleanup_free_ char *line = NULL;
66 p = procfs_file_alloca(pid, "stat");
68 r = read_one_line_file(p, &line);
74 p = strrchr(line, ')');
80 if (sscanf(p, " %c", &state) != 1)
83 return (unsigned char) state;
86 int get_process_comm(pid_t pid, char **name) {
93 p = procfs_file_alloca(pid, "comm");
95 r = read_one_line_file(p, name);
102 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
103 _cleanup_fclose_ FILE *f = NULL;
111 p = procfs_file_alloca(pid, "cmdline");
120 if (max_length == 0) {
121 size_t len = 0, allocated = 0;
123 while ((c = getc(f)) != EOF) {
125 if (!GREEDY_REALLOC(r, allocated, len+2)) {
130 r[len++] = isprint(c) ? c : ' ';
140 r = new(char, max_length);
146 while ((c = getc(f)) != EOF) {
168 size_t n = MIN(left-1, 3U);
175 /* Kernel threads have no argv[] */
177 _cleanup_free_ char *t = NULL;
185 h = get_process_comm(pid, &t);
189 r = strjoin("[", t, "]", NULL);
198 #if 0 /// UNNEEDED by elogind
199 void rename_process(const char name[8]) {
202 /* This is a like a poor man's setproctitle(). It changes the
203 * comm field, argv[0], and also the glibc's internally used
204 * name of the process. For the first one a limit of 16 chars
205 * applies, to the second one usually one of 10 (i.e. length
206 * of "/sbin/init"), to the third one one of 7 (i.e. length of
207 * "systemd"). If you pass a longer string it will be
210 prctl(PR_SET_NAME, name);
212 if (program_invocation_name)
213 strncpy(program_invocation_name, name, strlen(program_invocation_name));
215 if (saved_argc > 0) {
219 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
221 for (i = 1; i < saved_argc; i++) {
225 memzero(saved_argv[i], strlen(saved_argv[i]));
231 int is_kernel_thread(pid_t pid) {
238 if (pid == 0 || pid == 1) /* pid 1, and we ourselves certainly aren't a kernel thread */
243 p = procfs_file_alloca(pid, "cmdline");
251 count = fread(&c, 1, 1, f);
255 /* Kernel threads have an empty cmdline */
258 return eof ? 1 : -errno;
263 #if 0 /// UNNEEDED by elogind
264 int get_process_capeff(pid_t pid, char **capeff) {
271 p = procfs_file_alloca(pid, "status");
273 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
281 static int get_process_link_contents(const char *proc_file, char **name) {
287 r = readlink_malloc(proc_file, name);
296 int get_process_exe(pid_t pid, char **name) {
303 p = procfs_file_alloca(pid, "exe");
304 r = get_process_link_contents(p, name);
308 d = endswith(*name, " (deleted)");
315 #if 0 /// UNNEEDED by elogind
316 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
317 _cleanup_fclose_ FILE *f = NULL;
327 p = procfs_file_alloca(pid, "status");
335 FOREACH_LINE(line, f, return -errno) {
340 if (startswith(l, field)) {
342 l += strspn(l, WHITESPACE);
344 l[strcspn(l, WHITESPACE)] = 0;
346 return parse_uid(l, uid);
353 int get_process_uid(pid_t pid, uid_t *uid) {
354 return get_process_id(pid, "Uid:", uid);
357 int get_process_gid(pid_t pid, gid_t *gid) {
358 assert_cc(sizeof(uid_t) == sizeof(gid_t));
359 return get_process_id(pid, "Gid:", gid);
362 int get_process_cwd(pid_t pid, char **cwd) {
367 p = procfs_file_alloca(pid, "cwd");
369 return get_process_link_contents(p, cwd);
372 int get_process_root(pid_t pid, char **root) {
377 p = procfs_file_alloca(pid, "root");
379 return get_process_link_contents(p, root);
382 int get_process_environ(pid_t pid, char **env) {
383 _cleanup_fclose_ FILE *f = NULL;
384 _cleanup_free_ char *outcome = NULL;
387 size_t allocated = 0, sz = 0;
392 p = procfs_file_alloca(pid, "environ");
401 while ((c = fgetc(f)) != EOF) {
402 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
406 outcome[sz++] = '\n';
408 sz += cescape_char(c, outcome + sz);
412 outcome = strdup("");
424 int get_process_ppid(pid_t pid, pid_t *_ppid) {
426 _cleanup_free_ char *line = NULL;
438 p = procfs_file_alloca(pid, "stat");
439 r = read_one_line_file(p, &line);
445 /* Let's skip the pid and comm fields. The latter is enclosed
446 * in () but does not escape any () in its value, so let's
447 * skip over it manually */
449 p = strrchr(line, ')');
461 if ((long unsigned) (pid_t) ppid != ppid)
464 *_ppid = (pid_t) ppid;
470 int wait_for_terminate(pid_t pid, siginfo_t *status) {
481 if (waitid(P_PID, pid, status, WEXITED) < 0) {
495 * < 0 : wait_for_terminate() failed to get the state of the
496 * process, the process was terminated by a signal, or
497 * failed for an unknown reason.
498 * >=0 : The process terminated normally, and its exit code is
501 * That is, success is indicated by a return value of zero, and an
502 * error is indicated by a non-zero value.
504 * A warning is emitted if the process terminates abnormally,
505 * and also if it returns non-zero unless check_exit_code is true.
507 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
514 r = wait_for_terminate(pid, &status);
516 return log_warning_errno(r, "Failed to wait for %s: %m", name);
518 if (status.si_code == CLD_EXITED) {
519 if (status.si_status != 0)
520 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
521 "%s failed with error code %i.", name, status.si_status);
523 log_debug("%s succeeded.", name);
525 return status.si_status;
526 } else if (status.si_code == CLD_KILLED ||
527 status.si_code == CLD_DUMPED) {
529 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
533 log_warning("%s failed due to unknown reason.", name);
537 void sigkill_wait(pid_t *pid) {
543 if (kill(*pid, SIGKILL) > 0)
544 (void) wait_for_terminate(*pid, NULL);
547 #if 0 /// UNNEEDED by elogind
548 int kill_and_sigcont(pid_t pid, int sig) {
551 r = kill(pid, sig) < 0 ? -errno : 0;
560 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
561 _cleanup_fclose_ FILE *f = NULL;
572 path = procfs_file_alloca(pid, "environ");
574 f = fopen(path, "re");
588 for (i = 0; i < sizeof(line)-1; i++) {
592 if (_unlikely_(c == EOF)) {
602 if (memcmp(line, field, l) == 0 && line[l] == '=') {
603 value = strdup(line + l + 1);
617 bool pid_is_unwaited(pid_t pid) {
618 /* Checks whether a PID is still valid at all, including a zombie */
623 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
626 if (kill(pid, 0) >= 0)
629 return errno != ESRCH;
632 bool pid_is_alive(pid_t pid) {
635 /* Checks whether a PID is still valid and not a zombie */
640 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
643 r = get_process_state(pid);
644 if (r == -ESRCH || r == 'Z')
650 #if 0 /// UNNEEDED by elogind
651 int pid_from_same_root_fs(pid_t pid) {
657 root = procfs_file_alloca(pid, "root");
659 return files_same(root, "/proc/1/root");
663 bool is_main_thread(void) {
664 static thread_local int cached = 0;
666 if (_unlikely_(cached == 0))
667 cached = getpid() == gettid() ? 1 : -1;
672 #if 0 /// UNNEEDED by elogind
673 noreturn void freeze(void) {
675 /* Make sure nobody waits for us on a socket anymore */
676 close_all_fds(NULL, 0);
684 bool oom_score_adjust_is_valid(int oa) {
685 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
688 unsigned long personality_from_string(const char *p) {
692 return PERSONALITY_INVALID;
694 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
695 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
696 * the same register size. */
698 architecture = architecture_from_string(p);
699 if (architecture < 0)
700 return PERSONALITY_INVALID;
702 if (architecture == native_architecture())
704 #ifdef SECONDARY_ARCHITECTURE
705 if (architecture == SECONDARY_ARCHITECTURE)
709 return PERSONALITY_INVALID;
712 const char* personality_to_string(unsigned long p) {
713 int architecture = _ARCHITECTURE_INVALID;
716 architecture = native_architecture();
717 #ifdef SECONDARY_ARCHITECTURE
718 else if (p == PER_LINUX32)
719 architecture = SECONDARY_ARCHITECTURE;
722 if (architecture < 0)
725 return architecture_to_string(architecture);
728 void valgrind_summary_hack(void) {
729 #ifdef HAVE_VALGRIND_VALGRIND_H
730 if (getpid() == 1 && RUNNING_ON_VALGRIND) {
732 pid = raw_clone(SIGCHLD, NULL);
734 log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
738 log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
739 (void) wait_for_terminate(pid, NULL);
745 static const char *const ioprio_class_table[] = {
746 [IOPRIO_CLASS_NONE] = "none",
747 [IOPRIO_CLASS_RT] = "realtime",
748 [IOPRIO_CLASS_BE] = "best-effort",
749 [IOPRIO_CLASS_IDLE] = "idle"
752 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
754 static const char *const sigchld_code_table[] = {
755 [CLD_EXITED] = "exited",
756 [CLD_KILLED] = "killed",
757 [CLD_DUMPED] = "dumped",
758 [CLD_TRAPPED] = "trapped",
759 [CLD_STOPPED] = "stopped",
760 [CLD_CONTINUED] = "continued",
763 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
765 static const char* const sched_policy_table[] = {
766 [SCHED_OTHER] = "other",
767 [SCHED_BATCH] = "batch",
768 [SCHED_IDLE] = "idle",
769 [SCHED_FIFO] = "fifo",
773 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);