How to Monitor Process RSS Memory in Python
Poll the VmRSS field from /proc/PID/status to watch a process's resident memory and alert on growth.
Python code
45 linesimport os
import time
import subprocess
import sys
def get_rss_mb(pid):
"""Return RSS memory in MB for a given process ID."""
try:
with open(f"/proc/{pid}/status", "r") as f:
for line in f:
if line.startswith("VmRSS:"):
return int(line.split()[1]) / 1024 # kB to MB
except (FileNotFoundError, ProcessLookupError):
return None
return None
def monitor_process(pid, interval=1.0, threshold=100.0, max_cycles=10):
"""Watch RSS of a process and alert if it grows beyond threshold."""
print(f"Monitoring PID {pid} every {interval}s (threshold: {threshold} MB)")
previous_rss = None
for cycle in range(max_cycles):
rss = get_rss_mb(pid)
if rss is None:
print(f"Cycle {cycle+1}: Process {pid} no longer exists.")
return
growth = ""
if previous_rss is not None:
delta = rss - previous_rss
growth = f" (Δ{delta:+.1f} MB)"
print(f"Cycle {cycle+1}: RSS = {rss:.1f} MB{growth}")
if rss > threshold:
print(f"ALERT: RSS exceed threshold {threshold} MB")
return
previous_rss = rss
time.sleep(interval)
if __name__ == "__main__":
if len(sys.argv) > 1:
target_pid = int(sys.argv[1])
else:
# Use another instance of this script as a demo target
child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(15)"])
target_pid = child.pid
print(f"Demo target spawned with PID {target_pid}")
monitor_process(target_pid, interval=0.5, threshold=200.0, max_cycles=5)
Output
Monitoring PID 12345 every 0.5s (threshold: 200.0 MB)
Cycle 1: RSS = 45.2 MB
Cycle 2: RSS = 45.5 MB (Δ+0.3 MB)
Cycle 3: RSS = 46.0 MB (Δ+0.5 MB)
Cycle 4: RSS = 46.3 MB (Δ+0.3 MB)
Cycle 5: RSS = 46.7 MB (Δ+0.4 MB)
How it works
The script reads /proc/{pid}/status and extracts the VmRSS line, which reports resident memory in kilobytes. Dividing by 1024 converts it to megabytes. If the process dies, FileNotFoundError is raised, and the script returns None, signaling the process is gone. The loop records deltas between samples to highlight growth, and stops early if the RSS exceeds the threshold to trigger an alert. This works only on Linux-compatible systems where /proc is available.
Common mistakes
- Forgetting that `VmRSS` is in kilobytes, not bytes or megabytes.
- Not handling `FileNotFoundError` when the process exits mid-poll.
- Assuming `/proc` exists on macOS or Windows — it's Linux-specific.
- Sleeping after reading RSS, causing the first sample to be delayed longer than the interval.
Variations
- Use `psutil.Process(pid).memory_info().rss` to get the same value cross-platform.
- Read `/proc/{pid}/smaps` to also capture shared and private memory breakdown.
Real-world use cases
- Monitoring a long-running server process to detect memory leaks before they crash the host.
- Tracking a spawned child process during automated tests to ensure it stays within memory limits.
- Watching a background worker in a container to trigger autoscaling or restart policies.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.