> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/leonardo02lobo/Memory-Monitor/llms.txt
> Use this file to discover all available pages before exploring further.

# ListDirectory

> Find the process with the highest VmRSS (Resident Set Size) memory usage

## Function Signature

```python theme={null}
ListDirectory() -> list[str, str] | None
```

## Overview

The `ListDirectory()` function scans all running processes on the system to identify the process consuming the most physical memory (VmRSS). It returns a list containing a formatted description string and the process ID (PID) as a string of the memory-intensive process.

<Note>
  Despite its name, this function analyzes process memory usage rather than listing directory contents. It operates by scanning the `/proc` filesystem to examine each running process's memory statistics.
</Note>

## Return Value

<ResponseField name="return" type="list[str, str] | None">
  Returns a list with two elements:

  <ResponseField name="[0]" type="str">
    A formatted description string containing:

    * Process name
    * Process ID (PID)
    * VmRSS value in kilobytes

    Format:

    ```
    El proceso con mayor VmRSS es 
     Name: {process_name}
     PID: {pid}
     VmRSS: {vmrss} kB
    ```
  </ResponseField>

  <ResponseField name="[1]" type="str">
    The PID of the process as a string
  </ResponseField>

  Returns `None` if no processes can be analyzed (rare edge case).
</ResponseField>

## How It Works

### Process Discovery

1. **Scans `/proc` directory**: Lists all entries in `/proc`
2. **Filters for PIDs**: Identifies numeric directories (each represents a running process)
3. **Iterates through processes**: Examines each process's status file

### Memory Analysis

For each process, the function:

1. **Opens `/proc/{pid}/status`**: Reads the process status file
2. **Extracts process name**: Parses the `Name:` field
3. **Reads VmRSS value**: Extracts the `VmRSS:` field (Resident Set Size)
4. **Tracks maximum**: Keeps track of the process with the highest VmRSS

<Note>
  **VmRSS (Resident Set Size)** represents the portion of memory occupied by a process that is held in RAM. This is "real" physical memory usage, excluding swapped-out memory pages.
</Note>

### Error Handling

The function gracefully handles two common exceptions:

* **FileNotFoundError**: Process terminated between directory listing and status file read
* **PermissionError**: Insufficient permissions to read certain process information (common for system processes)

These exceptions are caught and the function continues to the next process without interruption.

## Example Output

```
El proceso con mayor VmRSS es 
 Name: chrome
 PID: 12345
 VmRSS: 2048576 kB
```

## Usage Example

<CodeGroup>
  ```python Basic Usage theme={null}
  from process_analyzer import ListDirectory

  # Find the process with highest memory usage
  result = ListDirectory()

  if result:
      description, pid = result
      print(description)
      print(f"\nProcess ID: {pid}")
  else:
      print("No processes found")
  ```

  ```python Extract Specific Values theme={null}
  from process_analyzer import ListDirectory

  def get_top_memory_process():
      """Get detailed information about the top memory consumer."""
      result = ListDirectory()
      
      if not result:
          return None
      
      description, pid = result
      
      # Parse the description to extract values
      lines = description.strip().split('\n')
      process_info = {}
      
      for line in lines[1:]:  # Skip first line
          if ':' in line:
              key, value = line.split(':', 1)
              process_info[key.strip()] = value.strip()
      
      return {
          'name': process_info.get('Name', 'Unknown'),
          'pid': process_info.get('PID', pid),
          'vmrss': process_info.get('VmRSS', 'Unknown'),
          'full_description': description
      }

  if __name__ == "__main__":
      top_process = get_top_memory_process()
      if top_process:
          print(f"Top Memory Consumer: {top_process['name']}")
          print(f"PID: {top_process['pid']}")
          print(f"Memory: {top_process['vmrss']}")
  ```

  ```python Monitoring Script theme={null}
  from process_analyzer import ListDirectory
  import time
  import os

  def monitor_top_process(duration=60, interval=5):
      """Monitor the top memory process over time."""
      print(f"Monitoring top memory process for {duration} seconds...\n")
      
      end_time = time.time() + duration
      previous_pid = None
      
      while time.time() < end_time:
          result = ListDirectory()
          
          if result:
              description, current_pid = result
              
              # Alert if the top process changed
              if previous_pid and current_pid != previous_pid:
                  print("\n⚠️  TOP PROCESS CHANGED!\n")
              
              print(f"[{time.strftime('%H:%M:%S')}]")
              print(description)
              print("-" * 40)
              
              previous_pid = current_pid
          
          time.sleep(interval)
      
      print("\nMonitoring complete.")

  if __name__ == "__main__":
      monitor_top_process(duration=30, interval=5)
  ```

  ```python Memory Alert System theme={null}
  from process_analyzer import ListDirectory
  import re

  def check_memory_threshold(threshold_mb=1024):
      """Alert if top process exceeds memory threshold."""
      result = ListDirectory()
      
      if not result:
          return False
      
      description, pid = result
      
      # Extract VmRSS value in kB
      match = re.search(r'VmRSS: (\d+) kB', description)
      if match:
          vmrss_kb = int(match.group(1))
          vmrss_mb = vmrss_kb / 1024
          
          if vmrss_mb > threshold_mb:
              print(f"⚠️  MEMORY ALERT!")
              print(f"Process {pid} is using {vmrss_mb:.2f} MB")
              print(f"Threshold: {threshold_mb} MB\n")
              print(description)
              return True
      
      return False

  if __name__ == "__main__":
      # Check if any process uses more than 2GB
      check_memory_threshold(threshold_mb=2048)
  ```
</CodeGroup>

## Source Code Reference

The implementation can be found in `process_analyzer.py:4-27`.

<Note>
  The function returns a list (not a tuple) with the second element being a string representation of the PID. To use the PID as an integer, convert it: `int(pid)`.
</Note>

## Technical Notes

### VmRSS vs Other Memory Metrics

* **VmRSS (Resident Set Size)**: Physical memory actually used (what this function reports)
* **VmSize**: Total virtual memory allocated (can be larger than physical RAM)
* **VmData**: Size of data segment
* **VmStk**: Size of stack

VmRSS is typically the most useful metric for understanding actual memory pressure on the system.

### Permissions

Some process information may not be accessible without elevated privileges. The function handles this gracefully by skipping processes it cannot read.

## See Also

* [InformationMemory](/api/memory-info) - Get overall system memory statistics
* [Quickstart Guide](/quickstart) - Get started with Memory Monitor
