]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/process-util.c
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 "raw-clone.h"
52 #include "signal-util.h"
53 #include "stat-util.h"
54 #include "string-table.h"
55 #include "string-util.h"
56 #include "user-util.h"
59 int get_process_state(pid_t pid
) {
63 _cleanup_free_
char *line
= NULL
;
67 p
= procfs_file_alloca(pid
, "stat");
69 r
= read_one_line_file(p
, &line
);
75 p
= strrchr(line
, ')');
81 if (sscanf(p
, " %c", &state
) != 1)
84 return (unsigned char) state
;
87 int get_process_comm(pid_t pid
, char **name
) {
94 p
= procfs_file_alloca(pid
, "comm");
96 r
= read_one_line_file(p
, name
);
103 int get_process_cmdline(pid_t pid
, size_t max_length
, bool comm_fallback
, char **line
) {
104 _cleanup_fclose_
FILE *f
= NULL
;
113 /* Retrieves a process' command line. Replaces unprintable characters while doing so by whitespace (coalescing
114 * multiple sequential ones into one). If max_length is != 0 will return a string of the specified size at most
115 * (the trailing NUL byte does count towards the length here!), abbreviated with a "..." ellipsis. If
116 * comm_fallback is true and the process has no command line set (the case for kernel threads), or has a
117 * command line that resolves to the empty string will return the "comm" name of the process instead.
119 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
120 * comm_fallback is false). */
122 p
= procfs_file_alloca(pid
, "cmdline");
131 if (max_length
== 1) {
133 /* If there's only room for one byte, return the empty string */
141 } else if (max_length
== 0) {
142 size_t len
= 0, allocated
= 0;
144 while ((c
= getc(f
)) != EOF
) {
146 if (!GREEDY_REALLOC(r
, allocated
, len
+3)) {
168 bool dotdotdot
= false;
171 r
= new(char, max_length
);
177 while ((c
= getc(f
)) != EOF
) {
204 if (max_length
<= 4) {
208 k
= r
+ max_length
- 4;
211 /* Eat up final spaces */
212 while (k
> r
&& isspace(k
[-1])) {
218 strncpy(k
, "...", left
-1);
224 /* Kernel threads have no argv[] */
226 _cleanup_free_
char *t
= NULL
;
234 h
= get_process_comm(pid
, &t
);
239 r
= strjoin("[", t
, "]");
245 if (l
+ 3 <= max_length
)
246 r
= strjoin("[", t
, "]");
247 else if (max_length
<= 6) {
249 r
= new(char, max_length
);
253 memcpy(r
, "[...]", max_length
-1);
258 t
[max_length
- 6] = 0;
260 /* Chop off final spaces */
262 while (e
> t
&& isspace(e
[-1]))
266 r
= strjoin("[", t
, "...]");
277 void rename_process(const char name
[8]) {
280 /* This is a like a poor man's setproctitle(). It changes the
281 * comm field, argv[0], and also the glibc's internally used
282 * name of the process. For the first one a limit of 16 chars
283 * applies, to the second one usually one of 10 (i.e. length
284 * of "/sbin/init"), to the third one one of 7 (i.e. length of
285 * "systemd"). If you pass a longer string it will be
288 (void) prctl(PR_SET_NAME
, name
);
290 if (program_invocation_name
)
291 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
293 if (saved_argc
> 0) {
297 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
299 for (i
= 1; i
< saved_argc
; i
++) {
303 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
308 int is_kernel_thread(pid_t pid
) {
315 if (pid
== 0 || pid
== 1) /* pid 1, and we ourselves certainly aren't a kernel thread */
320 p
= procfs_file_alloca(pid
, "cmdline");
328 count
= fread(&c
, 1, 1, f
);
332 /* Kernel threads have an empty cmdline */
335 return eof
? 1 : -errno
;
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
);
356 static int get_process_link_contents(const char *proc_file
, char **name
) {
362 r
= readlink_malloc(proc_file
, name
);
371 int get_process_exe(pid_t pid
, char **name
) {
378 p
= procfs_file_alloca(pid
, "exe");
379 r
= get_process_link_contents(p
, name
);
383 d
= endswith(*name
, " (deleted)");
390 static int get_process_id(pid_t pid
, const char *field
, uid_t
*uid
) {
391 _cleanup_fclose_
FILE *f
= NULL
;
398 p
= procfs_file_alloca(pid
, "status");
406 FOREACH_LINE(line
, f
, return -errno
) {
411 if (startswith(l
, field
)) {
413 l
+= strspn(l
, WHITESPACE
);
415 l
[strcspn(l
, WHITESPACE
)] = 0;
417 return parse_uid(l
, uid
);
424 int get_process_uid(pid_t pid
, uid_t
*uid
) {
425 return get_process_id(pid
, "Uid:", uid
);
428 int get_process_gid(pid_t pid
, gid_t
*gid
) {
429 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
430 return get_process_id(pid
, "Gid:", gid
);
433 int get_process_cwd(pid_t pid
, char **cwd
) {
438 p
= procfs_file_alloca(pid
, "cwd");
440 return get_process_link_contents(p
, cwd
);
443 int get_process_root(pid_t pid
, char **root
) {
448 p
= procfs_file_alloca(pid
, "root");
450 return get_process_link_contents(p
, root
);
453 int get_process_environ(pid_t pid
, char **env
) {
454 _cleanup_fclose_
FILE *f
= NULL
;
455 _cleanup_free_
char *outcome
= NULL
;
458 size_t allocated
= 0, sz
= 0;
463 p
= procfs_file_alloca(pid
, "environ");
472 while ((c
= fgetc(f
)) != EOF
) {
473 if (!GREEDY_REALLOC(outcome
, allocated
, sz
+ 5))
477 outcome
[sz
++] = '\n';
479 sz
+= cescape_char(c
, outcome
+ sz
);
483 outcome
= strdup("");
495 int get_process_ppid(pid_t pid
, pid_t
*_ppid
) {
497 _cleanup_free_
char *line
= NULL
;
509 p
= procfs_file_alloca(pid
, "stat");
510 r
= read_one_line_file(p
, &line
);
516 /* Let's skip the pid and comm fields. The latter is enclosed
517 * in () but does not escape any () in its value, so let's
518 * skip over it manually */
520 p
= strrchr(line
, ')');
532 if ((long unsigned) (pid_t
) ppid
!= ppid
)
535 *_ppid
= (pid_t
) ppid
;
540 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
551 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
556 return negative_errno();
565 * < 0 : wait_for_terminate() failed to get the state of the
566 * process, the process was terminated by a signal, or
567 * failed for an unknown reason.
568 * >=0 : The process terminated normally, and its exit code is
571 * That is, success is indicated by a return value of zero, and an
572 * error is indicated by a non-zero value.
574 * A warning is emitted if the process terminates abnormally,
575 * and also if it returns non-zero unless check_exit_code is true.
577 int wait_for_terminate_and_warn(const char *name
, pid_t pid
, bool check_exit_code
) {
584 r
= wait_for_terminate(pid
, &status
);
586 return log_warning_errno(r
, "Failed to wait for %s: %m", name
);
588 if (status
.si_code
== CLD_EXITED
) {
589 if (status
.si_status
!= 0)
590 log_full(check_exit_code
? LOG_WARNING
: LOG_DEBUG
,
591 "%s failed with error code %i.", name
, status
.si_status
);
593 log_debug("%s succeeded.", name
);
595 return status
.si_status
;
596 } else if (status
.si_code
== CLD_KILLED
||
597 status
.si_code
== CLD_DUMPED
) {
599 log_warning("%s terminated by signal %s.", name
, signal_to_string(status
.si_status
));
603 log_warning("%s failed due to unknown reason.", name
);
607 void sigkill_wait(pid_t pid
) {
610 if (kill(pid
, SIGKILL
) > 0)
611 (void) wait_for_terminate(pid
, NULL
);
614 void sigkill_waitp(pid_t
*pid
) {
623 int kill_and_sigcont(pid_t pid
, int sig
) {
626 r
= kill(pid
, sig
) < 0 ? -errno
: 0;
628 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
629 * affected by a process being suspended anyway. */
630 if (r
>= 0 && !IN_SET(SIGCONT
, SIGKILL
))
631 (void) kill(pid
, SIGCONT
);
636 int getenv_for_pid(pid_t pid
, const char *field
, char **_value
) {
637 _cleanup_fclose_
FILE *f
= NULL
;
648 path
= procfs_file_alloca(pid
, "environ");
650 f
= fopen(path
, "re");
664 for (i
= 0; i
< sizeof(line
)-1; i
++) {
668 if (_unlikely_(c
== EOF
)) {
678 if (strneq(line
, field
, l
) && line
[l
] == '=') {
679 value
= strdup(line
+ l
+ 1);
693 bool pid_is_unwaited(pid_t pid
) {
694 /* Checks whether a PID is still valid at all, including a zombie */
699 if (pid
<= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
702 if (kill(pid
, 0) >= 0)
705 return errno
!= ESRCH
;
708 bool pid_is_alive(pid_t pid
) {
711 /* Checks whether a PID is still valid and not a zombie */
716 if (pid
<= 1) /* If we or PID 1 would be a zombie, this code would not be running */
719 r
= get_process_state(pid
);
720 if (r
== -ESRCH
|| r
== 'Z')
726 int pid_from_same_root_fs(pid_t pid
) {
732 root
= procfs_file_alloca(pid
, "root");
734 return files_same(root
, "/proc/1/root");
737 bool is_main_thread(void) {
738 static thread_local
int cached
= 0;
740 if (_unlikely_(cached
== 0))
741 cached
= getpid() == gettid() ? 1 : -1;
746 noreturn
void freeze(void) {
750 /* Make sure nobody waits for us on a socket anymore */
751 close_all_fds(NULL
, 0);
759 bool oom_score_adjust_is_valid(int oa
) {
760 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;
763 unsigned long personality_from_string(const char *p
) {
767 return PERSONALITY_INVALID
;
769 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
770 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
771 * the same register size. */
773 architecture
= architecture_from_string(p
);
774 if (architecture
< 0)
775 return PERSONALITY_INVALID
;
777 if (architecture
== native_architecture())
779 #ifdef SECONDARY_ARCHITECTURE
780 if (architecture
== SECONDARY_ARCHITECTURE
)
784 return PERSONALITY_INVALID
;
787 const char* personality_to_string(unsigned long p
) {
788 int architecture
= _ARCHITECTURE_INVALID
;
791 architecture
= native_architecture();
792 #ifdef SECONDARY_ARCHITECTURE
793 else if (p
== PER_LINUX32
)
794 architecture
= SECONDARY_ARCHITECTURE
;
797 if (architecture
< 0)
800 return architecture_to_string(architecture
);
803 void valgrind_summary_hack(void) {
804 #ifdef HAVE_VALGRIND_VALGRIND_H
805 if (getpid() == 1 && RUNNING_ON_VALGRIND
) {
807 pid
= raw_clone(SIGCHLD
);
809 log_emergency_errno(errno
, "Failed to fork off valgrind helper: %m");
813 log_info("Spawned valgrind helper as PID "PID_FMT
".", pid
);
814 (void) wait_for_terminate(pid
, NULL
);
820 int pid_compare_func(const void *a
, const void *b
) {
821 const pid_t
*p
= a
, *q
= b
;
823 /* Suitable for usage in qsort() */
832 static const char *const ioprio_class_table
[] = {
833 [IOPRIO_CLASS_NONE
] = "none",
834 [IOPRIO_CLASS_RT
] = "realtime",
835 [IOPRIO_CLASS_BE
] = "best-effort",
836 [IOPRIO_CLASS_IDLE
] = "idle"
839 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
841 static const char *const sigchld_code_table
[] = {
842 [CLD_EXITED
] = "exited",
843 [CLD_KILLED
] = "killed",
844 [CLD_DUMPED
] = "dumped",
845 [CLD_TRAPPED
] = "trapped",
846 [CLD_STOPPED
] = "stopped",
847 [CLD_CONTINUED
] = "continued",
850 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
852 static const char* const sched_policy_table
[] = {
853 [SCHED_OTHER
] = "other",
854 [SCHED_BATCH
] = "batch",
855 [SCHED_IDLE
] = "idle",
856 [SCHED_FIFO
] = "fifo",
860 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);