Skip to content

Instantly share code, notes, and snippets.

@rindeal
Last active April 19, 2024 10:10
Show Gist options
  • Save rindeal/9f346a98e3853a23f00a227b602e0990 to your computer and use it in GitHub Desktop.
Save rindeal/9f346a98e3853a23f00a227b602e0990 to your computer and use it in GitHub Desktop.
Print process call stack. Pure BASH function.
#!/bin/bash
# based on https://stackoverflow.com/a/1438241/2566213
# pure BASH solution
print_process_call_stack() {
local -a trace=()
local -- cmdline
local -i pid=$$ ppid
while (( pid )) ; do
cmdline="$(
while read -r -d $'\0' f ; do
printf "%s " "${f}"
done < "/proc/${pid}/cmdline"
)"
trace+=( "$(printf "[%7d]: %s" "${pid}" "${cmdline}" )" )
ppid="$(
while read -r key val1 ; do
if [[ "${key}" == "PPid:" ]] ; then
echo "${val1}"
break
fi
done < "/proc/${pid}/status"
)"
pid=${ppid}
done
echo "Backtrace of '$0':"
for (( i=${#trace[@]} - 1 ; i >= 0 ; i-- )) ; do
printf " %s\n" "${trace[$i]}"
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment