Skip to content

Instantly share code, notes, and snippets.

@jrelo
Created July 25, 2024 18:21
Show Gist options
  • Save jrelo/e2a4bdad28e17e863ea53c3a835b1a9b to your computer and use it in GitHub Desktop.
Save jrelo/e2a4bdad28e17e863ea53c3a835b1a9b to your computer and use it in GitHub Desktop.
Find processes with large heap regions
#!/bin/bash
get_heap_size() {
local pid=$1
local heap_size=0
# Read the /proc/[pid]/maps file
while read -r line; do
if [[ "$line" == *"heap"* ]]; then
local start_addr=$(echo "$line" | awk '{print $1}' | cut -d'-' -f1)
local end_addr=$(echo "$line" | awk '{print $1}' | cut -d'-' -f2)
local start_dec=$((0x$start_addr))
local end_dec=$((0x$end_addr))
local size=$((end_dec - start_dec))
heap_size=$((heap_size + size))
fi
done < "/proc/$pid/maps"
echo "$heap_size"
}
# threshold in bytes
THRESHOLD=$((100 * 1024 * 1024)) # 100 MB
echo "PID HEAP SIZE (MB) COMMAND"
echo "--------------------------------"
for pid in /proc/[0-9]*; do
pid=$(basename "$pid")
if [[ -f "/proc/$pid/maps" ]]; then
heap_size=$(get_heap_size "$pid")
if [[ "$heap_size" -gt "$THRESHOLD" ]]; then
# Get the command name
command=$(cat "/proc/$pid/comm")
heap_size_mb=$((heap_size / 1024 / 1024))
printf "%-5s %-15s %s\n" "$pid" "$heap_size_mb" "$command"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment