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;
112 /* Retrieves a process' command line. Replaces unprintable characters while doing so by whitespace (coalescing
113 * multiple sequential ones into one). If max_length is != 0 will return a string of the specified size at most
114 * (the trailing NUL byte does count towards the length here!), abbreviated with a "..." ellipsis. If
115 * comm_fallback is true and the process has no command line set (the case for kernel threads), or has a
116 * command line that resolves to the empty string will return the "comm" name of the process instead.
118 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
119 * comm_fallback is false). */
121 p = procfs_file_alloca(pid, "cmdline");
130 if (max_length == 1) {
132 /* If there's only room for one byte, return the empty string */
140 } else if (max_length == 0) {
141 size_t len = 0, allocated = 0;
143 while ((c = getc(f)) != EOF) {
145 if (!GREEDY_REALLOC(r, allocated, len+3)) {
165 bool dotdotdot = false;
168 r = new(char, max_length);
174 while ((c = getc(f)) != EOF) {
201 if (max_length <= 4) {
205 k = r + max_length - 4;
208 /* Eat up final spaces */
209 while (k > r && isspace(k[-1])) {
215 strncpy(k, "...", left-1);
221 /* Kernel threads have no argv[] */
223 _cleanup_free_ char *t = NULL;
231 h = get_process_comm(pid, &t);
236 r = strjoin("[", t, "]", NULL);
242 if (l + 3 <= max_length)
243 r = strjoin("[", t, "]", NULL);
244 else if (max_length <= 6) {
246 r = new(char, max_length);
250 memcpy(r, "[...]", max_length-1);
255 t[max_length - 6] = 0;
257 /* Chop off final spaces */
259 while (e > t && isspace(e[-1]))
263 r = strjoin("[", t, "...]", NULL);
274 #if 0 /// UNNEEDED by elogind
275 void rename_process(const char name[8]) {
278 /* This is a like a poor man's setproctitle(). It changes the
279 * comm field, argv[0], and also the glibc's internally used
280 * name of the process. For the first one a limit of 16 chars
281 * applies, to the second one usually one of 10 (i.e. length
282 * of "/sbin/init"), to the third one one of 7 (i.e. length of
283 * "systemd"). If you pass a longer string it will be
286 (void) prctl(PR_SET_NAME, name);
288 if (program_invocation_name)
289 strncpy(program_invocation_name, name, strlen(program_invocation_name));
291 if (saved_argc > 0) {
295 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
297 for (i = 1; i < saved_argc; i++) {
301 memzero(saved_argv[i], strlen(saved_argv[i]));
307 int is_kernel_thread(pid_t pid) {
314 if (pid == 0 || pid == 1) /* pid 1, and we ourselves certainly aren't a kernel thread */
319 p = procfs_file_alloca(pid, "cmdline");
327 count = fread(&c, 1, 1, f);
331 /* Kernel threads have an empty cmdline */
334 return eof ? 1 : -errno;
339 #if 0 /// UNNEEDED by elogind
340 int get_process_capeff(pid_t pid, char **capeff) {
347 p = procfs_file_alloca(pid, "status");
349 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
357 static int get_process_link_contents(const char *proc_file, char **name) {
363 r = readlink_malloc(proc_file, name);
372 int get_process_exe(pid_t pid, char **name) {
379 p = procfs_file_alloca(pid, "exe");
380 r = get_process_link_contents(p, name);
384 d = endswith(*name, " (deleted)");
391 #if 0 /// UNNEEDED by elogind
392 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
393 _cleanup_fclose_ FILE *f = NULL;
400 p = procfs_file_alloca(pid, "status");
408 FOREACH_LINE(line, f, return -errno) {
413 if (startswith(l, field)) {
415 l += strspn(l, WHITESPACE);
417 l[strcspn(l, WHITESPACE)] = 0;
419 return parse_uid(l, uid);
426 int get_process_uid(pid_t pid, uid_t *uid) {
427 return get_process_id(pid, "Uid:", uid);
430 int get_process_gid(pid_t pid, gid_t *gid) {
431 assert_cc(sizeof(uid_t) == sizeof(gid_t));
432 return get_process_id(pid, "Gid:", gid);
435 int get_process_cwd(pid_t pid, char **cwd) {
440 p = procfs_file_alloca(pid, "cwd");
442 return get_process_link_contents(p, cwd);
445 int get_process_root(pid_t pid, char **root) {
450 p = procfs_file_alloca(pid, "root");
452 return get_process_link_contents(p, root);
455 int get_process_environ(pid_t pid, char **env) {
456 _cleanup_fclose_ FILE *f = NULL;
457 _cleanup_free_ char *outcome = NULL;
460 size_t allocated = 0, sz = 0;
465 p = procfs_file_alloca(pid, "environ");
474 while ((c = fgetc(f)) != EOF) {
475 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
479 outcome[sz++] = '\n';
481 sz += cescape_char(c, outcome + sz);
485 outcome = strdup("");
497 int get_process_ppid(pid_t pid, pid_t *_ppid) {
499 _cleanup_free_ char *line = NULL;
511 p = procfs_file_alloca(pid, "stat");
512 r = read_one_line_file(p, &line);
518 /* Let's skip the pid and comm fields. The latter is enclosed
519 * in () but does not escape any () in its value, so let's
520 * skip over it manually */
522 p = strrchr(line, ')');
534 if ((long unsigned) (pid_t) ppid != ppid)
537 *_ppid = (pid_t) ppid;
543 int wait_for_terminate(pid_t pid, siginfo_t *status) {
554 if (waitid(P_PID, pid, status, WEXITED) < 0) {
568 * < 0 : wait_for_terminate() failed to get the state of the
569 * process, the process was terminated by a signal, or
570 * failed for an unknown reason.
571 * >=0 : The process terminated normally, and its exit code is
574 * That is, success is indicated by a return value of zero, and an
575 * error is indicated by a non-zero value.
577 * A warning is emitted if the process terminates abnormally,
578 * and also if it returns non-zero unless check_exit_code is true.
580 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
587 r = wait_for_terminate(pid, &status);
589 return log_warning_errno(r, "Failed to wait for %s: %m", name);
591 if (status.si_code == CLD_EXITED) {
592 if (status.si_status != 0)
593 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
594 "%s failed with error code %i.", name, status.si_status);
596 log_debug("%s succeeded.", name);
598 return status.si_status;
599 } else if (status.si_code == CLD_KILLED ||
600 status.si_code == CLD_DUMPED) {
602 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
606 log_warning("%s failed due to unknown reason.", name);
610 #if 0 /// UNNEEDED by elogind
611 void sigkill_wait(pid_t pid) {
614 if (kill(pid, SIGKILL) > 0)
615 (void) wait_for_terminate(pid, NULL);
618 void sigkill_waitp(pid_t *pid) {
627 int kill_and_sigcont(pid_t pid, int sig) {
630 r = kill(pid, sig) < 0 ? -errno : 0;
639 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
640 _cleanup_fclose_ FILE *f = NULL;
651 path = procfs_file_alloca(pid, "environ");
653 f = fopen(path, "re");
667 for (i = 0; i < sizeof(line)-1; i++) {
671 if (_unlikely_(c == EOF)) {
681 if (memcmp(line, field, l) == 0 && line[l] == '=') {
682 value = strdup(line + l + 1);
696 bool pid_is_unwaited(pid_t pid) {
697 /* Checks whether a PID is still valid at all, including a zombie */
702 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
705 if (kill(pid, 0) >= 0)
708 return errno != ESRCH;
711 bool pid_is_alive(pid_t pid) {
714 /* Checks whether a PID is still valid and not a zombie */
719 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
722 r = get_process_state(pid);
723 if (r == -ESRCH || r == 'Z')
729 #if 0 /// UNNEEDED by elogind
730 int pid_from_same_root_fs(pid_t pid) {
736 root = procfs_file_alloca(pid, "root");
738 return files_same(root, "/proc/1/root");
742 bool is_main_thread(void) {
743 static thread_local int cached = 0;
745 if (_unlikely_(cached == 0))
746 cached = getpid() == gettid() ? 1 : -1;
751 #if 0 /// UNNEEDED by elogind
752 noreturn void freeze(void) {
756 /* Make sure nobody waits for us on a socket anymore */
757 close_all_fds(NULL, 0);
765 bool oom_score_adjust_is_valid(int oa) {
766 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
769 unsigned long personality_from_string(const char *p) {
773 return PERSONALITY_INVALID;
775 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
776 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
777 * the same register size. */
779 architecture = architecture_from_string(p);
780 if (architecture < 0)
781 return PERSONALITY_INVALID;
783 if (architecture == native_architecture())
785 #ifdef SECONDARY_ARCHITECTURE
786 if (architecture == SECONDARY_ARCHITECTURE)
790 return PERSONALITY_INVALID;
793 const char* personality_to_string(unsigned long p) {
794 int architecture = _ARCHITECTURE_INVALID;
797 architecture = native_architecture();
798 #ifdef SECONDARY_ARCHITECTURE
799 else if (p == PER_LINUX32)
800 architecture = SECONDARY_ARCHITECTURE;
803 if (architecture < 0)
806 return architecture_to_string(architecture);
809 void valgrind_summary_hack(void) {
810 #ifdef HAVE_VALGRIND_VALGRIND_H
811 if (getpid() == 1 && RUNNING_ON_VALGRIND) {
813 pid = raw_clone(SIGCHLD, NULL);
815 log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
819 log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
820 (void) wait_for_terminate(pid, NULL);
826 int pid_compare_func(const void *a, const void *b) {
827 const pid_t *p = a, *q = b;
829 /* Suitable for usage in qsort() */
838 static const char *const ioprio_class_table[] = {
839 [IOPRIO_CLASS_NONE] = "none",
840 [IOPRIO_CLASS_RT] = "realtime",
841 [IOPRIO_CLASS_BE] = "best-effort",
842 [IOPRIO_CLASS_IDLE] = "idle"
845 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
847 static const char *const sigchld_code_table[] = {
848 [CLD_EXITED] = "exited",
849 [CLD_KILLED] = "killed",
850 [CLD_DUMPED] = "dumped",
851 [CLD_TRAPPED] = "trapped",
852 [CLD_STOPPED] = "stopped",
853 [CLD_CONTINUED] = "continued",
856 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
858 static const char* const sched_policy_table[] = {
859 [SCHED_OTHER] = "other",
860 [SCHED_BATCH] = "batch",
861 [SCHED_IDLE] = "idle",
862 [SCHED_FIFO] = "fifo",
866 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);