HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/basic/process-util.c

80,575 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: bcee9c39d1c691fd8f4fc26f16e925d3ccd6fa54

Lines 1–1000 of 2,419

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <linux/oom.h>
#include <pthread.h>
#include <spawn.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/personality.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <syslog.h>
#include <threads.h>
#include <unistd.h>
#if HAVE_VALGRIND_VALGRIND_H
#include <valgrind/valgrind.h>
#endif
 
#include "sd-messages.h"
 
#include "alloc-util.h"
#include "architecture.h"
#include "argv-util.h"
#include "bitfield.h"
#include "capability-util.h"
#include "cgroup-util.h"
#include "dirent-util.h"
#include "dlfcn-util.h"
#include "errno-util.h"
#include "escape.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "io-util.h"
#include "iovec-util.h"
#include "locale-util.h"
#include "log.h"
#include "memory-util.h"
#include "mountpoint-util.h"
#include "namespace-util.h"
#include "nulstr-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "pidfd-util.h"
#include "pidref.h"
#include "process-util.h"
#include "raw-clone.h"
#include "rlimit-util.h"
#include "signal-util.h"
#include "socket-util.h"
#include "stat-util.h"
#include "stdio-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "time-util.h"
#include "user-util.h"
 
/* The kernel limits userspace processes to TASK_COMM_LEN (16 bytes), but allows higher values for its own
 * workers, e.g. "kworker/u9:3-kcryptd/253:0". Let's pick a fixed smallish limit that will work for the kernel.
 */
#define COMM_MAX_LEN 128
 
static int get_process_state(pid_t pid) {
        _cleanup_free_ char *line = NULL;
        const char *p;
        char state;
        int r;
 
        assert(pid >= 0);
 
        /* Shortcut: if we are enquired about our own state, we are obviously running */
        if (pid == 0 || pid == getpid_cached())
                return (unsigned char) 'R';
 
        p = procfs_file_alloca(pid, "stat");
 
        r = read_one_line_file(p, &line);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        p = strrchr(line, ')');
        if (!p)
                return -EIO;
 
        p++;
 
        if (sscanf(p, " %c", &state) != 1)
                return -EIO;
 
        return (unsigned char) state;
}
 
int pid_get_comm(pid_t pid, char **ret) {
        _cleanup_free_ char *escaped = NULL, *comm = NULL;
        int r;
 
        assert(pid >= 0);
        assert(ret);
 
        if (pid == 0 || pid == getpid_cached()) {
                comm = new0(char, TASK_COMM_LEN + 1); /* Must fit in 16 byte according to prctl(2) */
                if (!comm)
                        return -ENOMEM;
 
                r = prctl_safe(PR_GET_NAME, (unsigned long) comm, 0, 0, 0);
                if (r < 0)
                        return r;
        } else {
                const char *p;
 
                p = procfs_file_alloca(pid, "comm");
 
                /* Note that process names of kernel threads can be much longer than TASK_COMM_LEN */
                r = read_one_line_file(p, &comm);
                if (r == -ENOENT)
                        return -ESRCH;
                if (r < 0)
                        return r;
        }
 
        escaped = new(char, COMM_MAX_LEN);
        if (!escaped)
                return -ENOMEM;
 
        /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
        cellescape(escaped, COMM_MAX_LEN, comm);
 
        *ret = TAKE_PTR(escaped);
        return 0;
}
 
int pidref_get_comm(const PidRef *pid, char **ret) {
        _cleanup_free_ char *comm = NULL;
        int r;
 
        if (!pidref_is_set(pid))
                return -ESRCH;
 
        if (pidref_is_remote(pid))
                return -EREMOTE;
 
        r = pid_get_comm(pid->pid, &comm);
        if (r < 0)
                return r;
 
        r = pidref_verify(pid);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = TAKE_PTR(comm);
        return 0;
}
 
static int pid_get_cmdline_nulstr(
                pid_t pid,
                size_t max_size,
                ProcessCmdlineFlags flags,
                char **ret,
                size_t *ret_size) {
 
        _cleanup_free_ char *t = NULL;
        const char *p;
        size_t k;
        int r;
 
        /* Retrieves a process' command line as a "sized nulstr", i.e. possibly without the last NUL, but
         * with a specified size.
         *
         * If PROCESS_CMDLINE_COMM_FALLBACK is specified in flags and the process has no command line set
         * (the case for kernel threads), or has a command line that resolves to the empty string, will
         * return the "comm" name of the process instead. This will use at most _SC_ARG_MAX bytes of input
         * data.
         *
         * Returns an error, 0 if output was read but is truncated, 1 otherwise.
         */
 
        p = procfs_file_alloca(pid, "cmdline");
        r = read_virtual_file(p, max_size, &t, &k); /* Let's assume that each input byte results in >= 1
                                                     * columns of output. We ignore zero-width codepoints. */
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        if (k == 0) {
                if (!(flags & PROCESS_CMDLINE_COMM_FALLBACK))
                        return -ENOENT;
 
                /* Kernel threads have no argv[] */
                _cleanup_free_ char *comm = NULL;
 
                r = pid_get_comm(pid, &comm);
                if (r < 0)
                        return r;
 
                free(t);
                t = strjoin("[", comm, "]");
                if (!t)
                        return -ENOMEM;
 
                k = strlen(t);
                r = k <= max_size;
                if (r == 0) /* truncation */
                        t[max_size] = '\0';
        }
 
        if (ret)
                *ret = TAKE_PTR(t);
        if (ret_size)
                *ret_size = k;
 
        return r;
}
 
int pid_get_cmdline(pid_t pid, size_t max_columns, ProcessCmdlineFlags flags, char **ret) {
        _cleanup_free_ char *t = NULL;
        size_t k;
        char *ans;
 
        assert(pid >= 0);
        assert(ret);
 
        /* Retrieve and format a command line. See above for discussion of retrieval options.
         *
         * There are two main formatting modes:
         *
         * - when PROCESS_CMDLINE_QUOTE is specified, output is quoted in C/Python style. If no shell special
         *   characters are present, this output can be copy-pasted into the terminal to execute. UTF-8
         *   output is assumed.
         *
         * - otherwise, a compact non-roundtrippable form is returned. Non-UTF8 bytes are replaced by �. The
         *   returned string is of the specified console width at most, abbreviated with an ellipsis.
         *
         * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
         * PROCESS_CMDLINE_COMM_FALLBACK is not specified). Returns 0 and sets *line otherwise. */
 
        int full = pid_get_cmdline_nulstr(pid, max_columns, flags, &t, &k);
        if (full < 0)
                return full;
 
        if (flags & (PROCESS_CMDLINE_QUOTE | PROCESS_CMDLINE_QUOTE_POSIX)) {
                ShellEscapeFlags shflags = SHELL_ESCAPE_EMPTY |
                        FLAGS_SET(flags, PROCESS_CMDLINE_QUOTE_POSIX) * SHELL_ESCAPE_POSIX;
 
                assert(!(flags & PROCESS_CMDLINE_USE_LOCALE));
 
                _cleanup_strv_free_ char **args = NULL;
 
                /* Drop trailing NULs, otherwise strv_parse_nulstr() adds additional empty strings at the end.
                 * See also issue #21186. */
                args = strv_parse_nulstr_full(t, k, /* drop_trailing_nuls= */ true);
                if (!args)
                        return -ENOMEM;
 
                ans = quote_command_line(args, shflags);
                if (!ans)
                        return -ENOMEM;
        } else {
                /* Arguments are separated by NULs. Let's replace those with spaces. */
                for (size_t i = 0; i < k - 1; i++)
                        if (t[i] == '\0')
                                t[i] = ' ';
 
                delete_trailing_chars(t, WHITESPACE);
 
                bool eight_bit = (flags & PROCESS_CMDLINE_USE_LOCALE) && !is_locale_utf8();
 
                ans = escape_non_printable_full(t, max_columns,
                                                eight_bit * XESCAPE_8_BIT | !full * XESCAPE_FORCE_ELLIPSIS);
                if (!ans)
                        return -ENOMEM;
 
                ans = str_realloc(ans);
        }
 
        *ret = ans;
        return 0;
}
 
int pidref_get_cmdline(const PidRef *pid, size_t max_columns, ProcessCmdlineFlags flags, char **ret) {
        _cleanup_free_ char *s = NULL;
        int r;
 
        if (!pidref_is_set(pid))
                return -ESRCH;
 
        if (pidref_is_remote(pid))
                return -EREMOTE;
 
        r = pid_get_cmdline(pid->pid, max_columns, flags, &s);
        if (r < 0)
                return r;
 
        r = pidref_verify(pid);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = TAKE_PTR(s);
        return 0;
}
 
int pid_get_cmdline_strv(pid_t pid, ProcessCmdlineFlags flags, char ***ret) {
        _cleanup_free_ char *t = NULL;
        char **args;
        size_t k;
        int r;
 
        assert(pid >= 0);
        assert((flags & ~PROCESS_CMDLINE_COMM_FALLBACK) == 0);
        assert(ret);
 
        r = pid_get_cmdline_nulstr(pid, SIZE_MAX, flags, &t, &k);
        if (r < 0)
                return r;
 
        args = strv_parse_nulstr_full(t, k, /* drop_trailing_nuls= */ true);
        if (!args)
                return -ENOMEM;
 
        *ret = args;
        return 0;
}
 
int pidref_get_cmdline_strv(const PidRef *pid, ProcessCmdlineFlags flags, char ***ret) {
        _cleanup_strv_free_ char **args = NULL;
        int r;
 
        if (!pidref_is_set(pid))
                return -ESRCH;
 
        if (pidref_is_remote(pid))
                return -EREMOTE;
 
        r = pid_get_cmdline_strv(pid->pid, flags, &args);
        if (r < 0)
                return r;
 
        r = pidref_verify(pid);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = TAKE_PTR(args);
 
        return 0;
}
 
int procfs_get_stat_flags(const char *path, unsigned long long *ret) {
        int r;
 
        assert(path);
        assert(ret);
 
        /* Read the 'flags' field (9th field, task->flags) from the given /proc/[pid]/stat or
         * /proc/[pid]/task/[tid]/stat file. */
 
        _cleanup_free_ char *line = NULL;
        r = read_one_line_file(path, &line);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        /* Skip past the comm field */
        char *q = strrchr(line, ')');
        if (!q)
                return -EINVAL;
        q++;
 
        /* Skip 6 fields to reach the flags field */
        for (size_t i = 0; i < 6; i++) {
                size_t l = strspn(q, WHITESPACE);
                if (l < 1)
                        return -EINVAL;
                q += l;
 
                l = strcspn(q, WHITESPACE);
                if (l < 1)
                        return -EINVAL;
                q += l;
        }
 
        /* Skip preceding whitespace */
        size_t l = strspn(q, WHITESPACE);
        if (l < 1)
                return -EINVAL;
        q += l;
 
        /* Truncate the rest */
        l = strcspn(q, WHITESPACE);
        if (l < 1)
                return -EINVAL;
        q[l] = 0;
 
        return safe_atollu(q, ret);
}
 
int pid_is_kernel_thread(pid_t pid) {
        int r;
 
        if (IN_SET(pid, 0, 1) || pid == getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
                return 0;
        if (!pid_is_valid(pid))
                return -EINVAL;
 
        const char *p = procfs_file_alloca(pid, "stat");
 
        unsigned long long flags;
        r = procfs_get_stat_flags(p, &flags);
        if (r < 0)
                return r;
 
        return !!(flags & PF_KTHREAD);
}
 
int pidref_is_kernel_thread(const PidRef *pid) {
        int result, r;
 
        if (!pidref_is_set(pid))
                return -ESRCH;
 
        if (pidref_is_remote(pid))
                return -EREMOTE;
 
        result = pid_is_kernel_thread(pid->pid);
        if (result < 0)
                return result;
 
        r = pidref_verify(pid); /* Verify that the PID wasn't reused since */
        if (r < 0)
                return r;
 
        return result;
}
 
static int get_process_link_contents(pid_t pid, const char *proc_file, char **ret) {
        const char *p;
        int r;
 
        assert(proc_file);
 
        p = procfs_file_alloca(pid, proc_file);
 
        r = readlink_malloc(p, ret);
        return (r == -ENOENT && proc_mounted() > 0) ? -ESRCH : r;
}
 
int get_process_exe(pid_t pid, char **ret) {
        char *d;
        int r;
 
        assert(pid >= 0);
 
        r = get_process_link_contents(pid, "exe", ret);
        if (r < 0)
                return r;
 
        if (ret) {
                d = endswith(*ret, " (deleted)");
                if (d)
                        *d = '\0';
        }
 
        return 0;
}
 
int pid_get_uid(pid_t pid, uid_t *ret) {
        int r;
 
        assert(pid >= 0);
        assert(ret);
 
        if (pid == 0 || pid == getpid_cached()) {
                *ret = getuid();
                return 0;
        }
 
        _cleanup_free_ char *v = NULL;
        r = procfs_file_get_field(pid, "status", "Uid", &v);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        return parse_uid(v, ret);
}
 
int pidref_get_uid(const PidRef *pid, uid_t *ret) {
        int r;
 
        if (!pidref_is_set(pid))
                return -ESRCH;
 
        if (pidref_is_remote(pid))
                return -EREMOTE;
 
        if (pid->fd >= 0) {
                r = pidfd_get_uid(pid->fd, ret);
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(r))
                        return r;
        }
 
        uid_t uid;
        r = pid_get_uid(pid->pid, &uid);
        if (r < 0)
                return r;
 
        r = pidref_verify(pid);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = uid;
        return 0;
}
 
int get_process_gid(pid_t pid, gid_t *ret) {
        int r;
 
        assert(pid >= 0);
        assert(ret);
 
        if (pid == 0 || pid == getpid_cached()) {
                *ret = getgid();
                return 0;
        }
 
        _cleanup_free_ char *v = NULL;
        r = procfs_file_get_field(pid, "status", "Gid", &v);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        return parse_gid(v, ret);
}
 
int get_process_cwd(pid_t pid, char **ret) {
        assert(pid >= 0);
 
        if (pid == 0 || pid == getpid_cached())
                return safe_getcwd(ret);
 
        return get_process_link_contents(pid, "cwd", ret);
}
 
int get_process_root(pid_t pid, char **ret) {
        assert(pid >= 0);
        return get_process_link_contents(pid, "root", ret);
}
 
#define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
 
int get_process_environ(pid_t pid, char **ret) {
        _cleanup_fclose_ FILE *f = NULL;
        _cleanup_free_ char *outcome = NULL;
        size_t sz = 0;
        const char *p;
        int r;
 
        assert(pid >= 0);
        assert(ret);
 
        p = procfs_file_alloca(pid, "environ");
 
        r = fopen_unlocked(p, "re", &f);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        for (;;) {
                char c;
 
                if (sz >= ENVIRONMENT_BLOCK_MAX)
                        return -ENOBUFS;
 
                if (!GREEDY_REALLOC(outcome, sz + 5))
                        return -ENOMEM;
 
                r = safe_fgetc(f, &c);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                if (c == '\0')
                        outcome[sz++] = '\n';
                else
                        sz += cescape_char(c, outcome + sz);
        }
 
        outcome[sz] = '\0';
        *ret = TAKE_PTR(outcome);
 
        return 0;
}
 
int pid_get_ppid(pid_t pid, pid_t *ret) {
        _cleanup_free_ char *line = NULL;
        unsigned long ppid;
        const char *p;
        int r;
 
        assert(pid >= 0);
 
        if (pid == 0)
                pid = getpid_cached();
        if (pid == 1) /* PID 1 has no parent, shortcut this case */
                return -EADDRNOTAVAIL;
 
        if (pid == getpid_cached()) {
                if (ret)
                        *ret = getppid();
                return 0;
        }
 
        p = procfs_file_alloca(pid, "stat");
        r = read_one_line_file(p, &line);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        /* Let's skip the pid and comm fields. The latter is enclosed in () but does not escape any () in its
         * value, so let's skip over it manually */
 
        p = strrchr(line, ')');
        if (!p)
                return -EIO;
        p++;
 
        if (sscanf(p, " "
                   "%*c "  /* state */
                   "%lu ", /* ppid */
                   &ppid) != 1)
                return -EIO;
 
        /* If ppid is zero the process has no parent. Which might be the case for PID 1 (caught above)
         * but also for processes originating in other namespaces that are inserted into a pidns.
         * Return a recognizable error in this case. */
        if (ppid == 0)
                return -EADDRNOTAVAIL;
 
        if ((pid_t) ppid < 0 || (unsigned long) (pid_t) ppid != ppid)
                return -ERANGE;
 
        if (ret)
                *ret = (pid_t) ppid;
 
        return 0;
}
 
int pidref_get_ppid(const PidRef *pidref, pid_t *ret) {
        int r;
 
        if (!pidref_is_set(pidref))
                return -ESRCH;
 
        if (pidref_is_remote(pidref))
                return -EREMOTE;
 
        if (pidref->fd >= 0) {
                r = pidfd_get_ppid(pidref->fd, ret);
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(r))
                        return r;
        }
 
        pid_t ppid;
        r = pid_get_ppid(pidref->pid, ret ? &ppid : NULL);
        if (r < 0)
                return r;
 
        r = pidref_verify(pidref);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = ppid;
        return 0;
}
 
int pidref_get_ppid_as_pidref(const PidRef *pidref, PidRef *ret) {
        pid_t ppid;
        int r;
 
        POINTER_MAY_BE_NULL(pidref);
        assert(ret);
 
        r = pidref_get_ppid(pidref, &ppid);
        if (r < 0)
                return r;
 
        for (unsigned attempt = 0; attempt < 16; attempt++) {
                _cleanup_(pidref_done) PidRef parent = PIDREF_NULL;
 
                r = pidref_set_pid(&parent, ppid);
                if (r < 0)
                        return r;
 
                /* If we have a pidfd of the original PID, let's verify that the process we acquired really
                 * is the parent still */
                if (pidref->fd >= 0) {
                        r = pidref_get_ppid(pidref, &ppid);
                        if (r < 0)
                                return r;
 
                        /* Did the PPID change since we queried it? if so we might have pinned the wrong
                         * process, if its PID got reused by now. Let's try again */
                        if (parent.pid != ppid)
                                continue;
                }
 
                *ret = TAKE_PIDREF(parent);
                return 0;
        }
 
        /* Give up after 16 tries */
        return -ENOTRECOVERABLE;
}
 
int pid_get_start_time(pid_t pid, usec_t *ret) {
        _cleanup_free_ char *line = NULL;
        const char *p;
        int r;
 
        assert(pid >= 0);
 
        p = procfs_file_alloca(pid, "stat");
        r = read_one_line_file(p, &line);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        /* Let's skip the pid and comm fields. The latter is enclosed in () but does not escape any () in its
         * value, so let's skip over it manually */
 
        p = strrchr(line, ')');
        if (!p)
                return -EIO;
        p++;
 
        unsigned long llu;
 
        if (sscanf(p, " "
                   "%*c " /* state */
                   "%*u " /* ppid */
                   "%*u " /* pgrp */
                   "%*u " /* session */
                   "%*u " /* tty_nr */
                   "%*u " /* tpgid */
                   "%*u " /* flags */
                   "%*u " /* minflt */
                   "%*u " /* cminflt */
                   "%*u " /* majflt */
                   "%*u " /* cmajflt */
                   "%*u " /* utime */
                   "%*u " /* stime */
                   "%*u " /* cutime */
                   "%*u " /* cstime */
                   "%*i " /* priority */
                   "%*i " /* nice */
                   "%*u " /* num_threads */
                   "%*u " /* itrealvalue */
                   "%lu ", /* starttime */
                   &llu) != 1)
                return -EIO;
 
        if (ret)
                *ret = jiffies_to_usec(llu); /* CLOCK_BOOTTIME */
 
        return 0;
}
 
int pidref_get_start_time(const PidRef *pid, usec_t *ret) {
        usec_t t;
        int r;
 
        if (!pidref_is_set(pid))
                return -ESRCH;
 
        if (pidref_is_remote(pid))
                return -EREMOTE;
 
        r = pid_get_start_time(pid->pid, ret ? &t : NULL);
        if (r < 0)
                return r;
 
        r = pidref_verify(pid);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = t;
 
        return 0;
}
 
int get_process_umask(pid_t pid, mode_t *ret) {
        _cleanup_free_ char *m = NULL;
        int r;
 
        assert(pid >= 0);
        assert(ret);
 
        r = procfs_file_get_field(pid, "status", "Umask", &m);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        return parse_mode(m, ret);
}
 
static int pid_get_sigmask(pid_t pid, const char *field_name, uint64_t *ret) {
        _cleanup_free_ char *field = NULL;
        int r;
 
        assert(pid >= 0);
        assert(field_name);
        assert(ret);
 
        r = procfs_file_get_field(pid, "status", field_name, &field);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        return safe_atou64_full(field, 16, ret);
}
 
static int pidref_has_sigmask(const PidRef *pidref, int sig, const char *field_name) {
        uint64_t mask;
        int r;
 
        if (!pidref_is_set(pidref))
                return -ESRCH;
        if (pidref_is_remote(pidref))
                return -EREMOTE;
        if (!SIGNAL_VALID(sig))
                return -EINVAL;
 
        r = pid_get_sigmask(pidref->pid, field_name, &mask);
        if (r < 0)
                return r;
 
        r = pidref_verify(pidref);
        if (r < 0)
                return r;
 
        return BIT_SET(mask, sig - 1);
}
 
int pidref_has_sigcgt(const PidRef *pidref, int sig) {
        return pidref_has_sigmask(pidref, sig, "SigCgt");
}
 
int pidref_has_sigblk(const PidRef *pidref, int sig) {
        return pidref_has_sigmask(pidref, sig, "SigBlk");
}
 
/*
 * Return values:
 * < 0 : pidref_wait_for_terminate() failed to get the state of the
 *       process, the process was terminated by a signal, or
 *       failed for an unknown reason.
 * >=0 : The process terminated normally, and its exit code is
 *       returned.
 *
 * That is, success is indicated by a return value of zero, and an
 * error is indicated by a non-zero value.
 *
 * A warning is emitted if the process terminates abnormally,
 * and also if it returns non-zero unless check_exit_code is true.
 */
int pidref_wait_for_terminate_and_check(const char *name, PidRef *pidref, WaitFlags flags) {
        int r;
 
        if (!pidref_is_set(pidref))
                return -ESRCH;
        if (pidref_is_remote(pidref))
                return -EREMOTE;
        if (pidref->pid == 1 || pidref_is_self(pidref))
                return -ECHILD;
 
        _cleanup_free_ char *buffer = NULL;
        if (!name) {
                r = pidref_get_comm(pidref, &buffer);
                if (r < 0)
                        log_debug_errno(r, "Failed to acquire process name of " PID_FMT ", ignoring: %m", pidref->pid);
                else
                        name = buffer;
        }
 
        int prio = flags & WAIT_LOG_ABNORMAL ? LOG_ERR : LOG_DEBUG;
 
        siginfo_t status;
        r = pidref_wait_for_terminate(pidref, &status);
        if (r < 0)
                return log_full_errno(prio, r, "Failed to wait for '%s': %m", strna(name));
 
        if (status.si_code == CLD_EXITED) {
                if (status.si_status != EXIT_SUCCESS)
                        log_full(flags & WAIT_LOG_NON_ZERO_EXIT_STATUS ? LOG_ERR : LOG_DEBUG,
                                 "'%s' failed with exit status %i.", strna(name), status.si_status);
                else
                        log_debug("'%s' succeeded.", name);
 
                return status.si_status;
 
        } else if (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED))
                return log_full_errno(prio, SYNTHETIC_ERRNO(EPROTO),
                                      "'%s' terminated by signal %s.", strna(name), signal_to_string(status.si_status));
 
        return log_full_errno(prio, SYNTHETIC_ERRNO(EPROTO),
                              "'%s' failed due to unknown reason.", strna(name));
}
 
int kill_and_sigcont(pid_t pid, int sig) {
        int r;
 
        r = RET_NERRNO(kill(pid, sig));
 
        /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
         * affected by a process being suspended anyway. */
        if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL))
                (void) kill(pid, SIGCONT);
 
        return r;
}
 
int getenv_for_pid(pid_t pid, const char *field, char **ret) {
        _cleanup_fclose_ FILE *f = NULL;
        const char *path;
        size_t sum = 0;
        int r;
 
        assert(pid >= 0);
        assert(field);
        assert(ret);
 
        if (pid == 0 || pid == getpid_cached())
                return strdup_to_full(ret, getenv(field));
 
        if (!pid_is_valid(pid))
                return -EINVAL;
 
        path = procfs_file_alloca(pid, "environ");
 
        r = fopen_unlocked(path, "re", &f);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        for (;;) {
                _cleanup_free_ char *line = NULL;
                const char *match;
 
                if (sum > ENVIRONMENT_BLOCK_MAX) /* Give up searching eventually */
                        return -ENOBUFS;
 
                r = read_nul_string(f, LONG_LINE_MAX, &line);
                if (r < 0)
                        return r;
                if (r == 0)  /* EOF */
                        break;
 
                sum += r;
 
                match = startswith(line, field);
                if (match && *match == '=')
                        return strdup_to_full(ret, match + 1);
        }
 
        *ret = NULL;
        return 0;
}
 
int pidref_is_my_child(PidRef *pid) {
        int r;
 
        if (!pidref_is_set(pid))
                return -ESRCH;
 
        if (pidref_is_remote(pid))
                return -EREMOTE;
 
        if (pid->pid == 1 || pidref_is_self(pid))
                return false;
 
        pid_t ppid;
        r = pidref_get_ppid(pid, &ppid);
        if (r == -EADDRNOTAVAIL) /* if this process is outside of our pidns, it is definitely not our child */