Monitoring Process Memory Usage in Linux: Commands and Techniques for Developers


4 views

When debugging performance issues or optimizing applications, checking a process's memory consumption is crucial. Here are the most useful commands:

// Basic process memory info
ps aux | grep [process_name]

// Detailed memory breakdown
pmap -x [pid]

// Interactive monitoring
top
htop

The Linux proc filesystem provides the most accurate memory data:

cat /proc/[pid]/status | grep -E 'VmSize|VmRSS|VmData'

// Example output:
VmSize:   102456 kB  // Virtual memory size
VmRSS:     42368 kB  // Resident set size (physical RAM used)
VmData:    24576 kB  // Data segment size

For long-running processes, consider these monitoring approaches:

// Continuous logging with watch
watch -n 5 'ps -p [pid] -o %mem,rss'

// Custom monitoring script
#!/bin/bash
while true; do
    ps -p $1 -o %mem,rss,cmd >> memory_log.txt
    sleep 10
done

For deeper analysis, these tools provide valuable insights:

  • Valgrind massif: Heap profiling tool
  • smem: Proportional set size reporting
  • sar: System activity reporter
// Example smem usage
smem -p -P [process_name]

// Valgrind heap profiling
valgrind --tool=massif ./your_program

Key concepts developers should understand:

  • Virtual vs physical memory allocation
  • Shared memory between processes
  • Memory leaks vs normal usage patterns
// Checking for shared libraries
cat /proc/[pid]/maps | grep '\.so'

// Identifying memory leaks
valgrind --leak-check=full ./your_program

When debugging performance issues or optimizing applications, checking a process's memory consumption is crucial. Linux provides multiple ways to inspect memory usage, each offering different levels of detail.

The simplest way is using the top command:

top -p [PID]

Or the more user-friendly htop:

htop

Both display real-time memory statistics including:

  • RES (Resident Memory): Physical RAM used
  • VIRT (Virtual Memory): Total address space
  • SHR (Shared Memory): Memory shared with other processes

For deeper inspection, read the process's status file:

cat /proc/[PID]/status | grep -i vm

Or check the smaps file for memory mapping details:

cat /proc/[PID]/smaps

The ps command provides flexible output formatting:

ps -p [PID] -o %mem,rss,vsz,cmd

Where:

  • %mem: Percentage of physical RAM used
  • rss: Resident Set Size in KB
  • vsz: Virtual Memory Size in KB

For application developers, these tools offer more insights:

valgrind --tool=massif ./your_program
ms_print massif.out.[PID]

Or use pmap for memory mapping analysis:

pmap -x [PID]

Create a simple bash script to log memory usage:

#!/bin/bash
while true; do
    ps -p $1 -o %mem,rss >> memory.log
    sleep 5
done

Run it with: ./mem_monitor.sh [PID]