Skip to content

Instantly share code, notes, and snippets.

@vcheckzen
Last active March 10, 2024 19:18
Show Gist options
  • Save vcheckzen/ff9be2d6f49f2660e2a6be9075a4a4fc to your computer and use it in GitHub Desktop.
Save vcheckzen/ff9be2d6f49f2660e2a6be9075a4a4fc to your computer and use it in GitHub Desktop.
Find ancestor and descendant of a process on Linux.
#!/bin/sh
find_ancestors() {
pid=$1
while [ "$pid" -ne 0 ]; do
echo "$pid"
pid=$(awk '{print $4}' /proc/"$pid"/stat 2>/dev/null)
done
}
find_children() {
parent_pid=$1
children=$(awk -v ppid="$parent_pid" '$4==ppid {print $1}' /proc/[0-9]*/stat 2>/dev/null)
for child in $children; do
echo "$child"
find_children "$child"
done
}
find_ancestors "$1"
find_children "$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment