get_own_pid() {
# This function being called in a subshell,
# it must returns the pid of the parent of the "cut" command parent
cut -d' ' -f4 < /proc/self/stat \
| xargs -I% sh -c 'cut -d" " -f4 < /proc/%/stat'
}
get_parent_pid() {
# Same thing but repeating the last command once more to get the parent one level above
cut -d' ' -f4 < /proc/self/stat \
| xargs -I% sh -c 'cut -d" " -f4 < /proc/%/stat' \
| xargs -I% sh -c 'cut -d" " -f4 < /proc/%/stat'
}
# Here pid is the same as the $$ pid because called from main process
MY_PID=$(get_own_pid)
echo "$$ == ${MY_PID}"
# Here called in a subprocess, the returned pid is different
(
MY_CHILD_PID=$(get_own_pid)
PARENT_PID_FROM_CHILD=$(get_parent_pid)
echo "$$ != ${MY_CHILD_PID}"
echo "$$ == ${PARENT_PID_FROM_CHILD}"
)