Last active
March 10, 2024 19:18
-
-
Save vcheckzen/ff9be2d6f49f2660e2a6be9075a4a4fc to your computer and use it in GitHub Desktop.
Find ancestor and descendant of a process on Linux.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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