2025-04-10 07:42:17 +00:00
|
|
|
#!/usr/bin/env bash
|
2021-01-02 04:21:44 +00:00
|
|
|
|
|
|
|
USAGE='
|
|
|
|
USAGE: rpid <pid|-h|-[-]help> [<root_name>=login]
|
|
|
|
|
2021-01-04 19:47:13 +00:00
|
|
|
pid The PID of the process for which you want to find the root
|
|
|
|
PID. Defaults to $$.
|
2021-01-02 04:21:44 +00:00
|
|
|
|
|
|
|
root_name
|
|
|
|
The name (not command line) of the root process, for which
|
|
|
|
to find the PID. Defaults to login.
|
|
|
|
|
|
|
|
EXAMPLES:
|
|
|
|
|
|
|
|
Any of these will display this help message.
|
|
|
|
|
|
|
|
rpid -h
|
|
|
|
rpid -help
|
|
|
|
rpid --help
|
|
|
|
|
|
|
|
Get the PID of the login process that is the ancestor of the current
|
|
|
|
process.
|
|
|
|
|
2021-01-04 19:47:13 +00:00
|
|
|
rpid
|
2021-10-26 02:29:52 +00:00
|
|
|
|
|
|
|
Get the PID of the first ancestor of the current process, if there
|
|
|
|
is no ancestor named "not_a_process."
|
|
|
|
|
|
|
|
rpid $$ not_a_process
|
|
|
|
|
|
|
|
Get the PID of the current process itself, if it is named
|
|
|
|
"current_process."
|
|
|
|
|
|
|
|
rpid $$ current_process
|
2021-01-02 04:21:44 +00:00
|
|
|
'
|
|
|
|
|
|
|
|
# Validate the arguments
|
2021-01-04 19:47:13 +00:00
|
|
|
if [[ "$#" -gt 2 ]]; then
|
2021-01-02 04:21:44 +00:00
|
|
|
printf '%s' "${USAGE}" 1>&2
|
2021-01-04 19:47:13 +00:00
|
|
|
exit 64
|
2021-01-02 04:21:44 +00:00
|
|
|
fi
|
|
|
|
|
2021-01-04 19:47:13 +00:00
|
|
|
pid="${1:-$$}"
|
2021-01-02 04:21:44 +00:00
|
|
|
|
|
|
|
# Check if the user needs help
|
|
|
|
if [[ "${pid}" =~ ^(-h|-(-)?help)$ ]]; then
|
|
|
|
printf '%s' "${USAGE}" 1>&2
|
|
|
|
exit 0
|
|
|
|
fi
|
|
|
|
|
|
|
|
root_name="${2:-login}"
|
|
|
|
|
2021-10-26 02:29:52 +00:00
|
|
|
prev_pid="${pid}"
|
|
|
|
current_pid="${pid}"
|
|
|
|
while [[ "${name}" != "${root_name}" && -r "/proc/${current_pid}/status" ]]; do
|
2021-01-02 04:21:44 +00:00
|
|
|
mapfile info < \
|
|
|
|
<(grep --null -E -m 2 '^(Name|PPid):' "/proc/${current_pid}/status" \
|
|
|
|
| sort | cut -f 2)
|
|
|
|
name="${info[0]##[[:space:]]}"
|
|
|
|
name="${name%%[[:space:]]}"
|
2021-10-26 02:29:52 +00:00
|
|
|
prev_pid="${current_pid}"
|
|
|
|
current_pid="${info[1]##[[:space:]]}"
|
|
|
|
current_pid="${current_pid%%[[:space:]]}"
|
2021-01-02 04:21:44 +00:00
|
|
|
done
|
|
|
|
|
2021-10-26 02:29:52 +00:00
|
|
|
printf '%s\n' "${prev_pid}"
|
2021-01-02 04:21:44 +00:00
|
|
|
if [[ "${name}" != "${root_name}" ]]; then exit 1; fi
|
|
|
|
|