How to show per‑process tree → pstree -p
How to Show Per-Process Tree → pstree -p
Table of Contents
1. [Introduction](#introduction)
2. [Prerequisites](#prerequisites)
3. [Understanding Process Trees](#understanding-process-trees)
4. [Basic pstree Command Usage](#basic-pstree-command-usage)
5. [Using pstree -p for Process IDs](#using-pstree--p-for-process-ids)
6. [Advanced pstree Options and Examples](#advanced-pstree-options-and-examples)
7. [Practical Use Cases](#practical-use-cases)
8. [Troubleshooting Common Issues](#troubleshooting-common-issues)
9. [Best Practices and Tips](#best-practices-and-tips)
10. [Alternative Tools and Methods](#alternative-tools-and-methods)
11. [Conclusion](#conclusion)
Introduction
The `pstree` command is a powerful Unix/Linux utility that displays running processes in a hierarchical tree format, making it easy to understand parent-child relationships between processes. When combined with the `-p` option, `pstree -p` shows process IDs (PIDs) alongside each process name, providing crucial information for system administrators, developers, and power users who need to monitor, debug, or manage system processes effectively.
This comprehensive guide will teach you everything you need to know about using `pstree -p` to visualize process trees with process IDs. You'll learn basic usage, advanced techniques, practical applications, and troubleshooting methods that will enhance your system administration and debugging skills.
Prerequisites
Before diving into the `pstree -p` command, ensure you have the following:
System Requirements
- A Unix-like operating system (Linux, macOS, BSD, etc.)
- Terminal or command-line access
- The `pstree` utility installed on your system
Installation Check
To verify if `pstree` is installed, run:
```bash
which pstree
```
If not installed, you can install it using your system's package manager:
Ubuntu/Debian:
```bash
sudo apt-get install psmisc
```
CentOS/RHEL/Fedora:
```bash
sudo yum install psmisc
or for newer versions
sudo dnf install psmisc
```
macOS (using Homebrew):
```bash
brew install pstree
```
Basic Knowledge Requirements
- Basic understanding of command-line interface
- Familiarity with process concepts in Unix/Linux
- Understanding of process IDs (PIDs) and parent-child relationships
Understanding Process Trees
What Are Process Trees?
A process tree represents the hierarchical relationship between processes running on a system. Every process (except the init process) has a parent process that created it. This creates a tree-like structure where:
- The root of the tree is typically the init process (PID 1)
- Each process can spawn child processes
- Child processes inherit certain attributes from their parents
- When a parent process terminates, its children may become orphaned
Why Process Trees Matter
Understanding process trees is crucial for:
- System Monitoring: Identifying resource-intensive process families
- Debugging: Tracing the origin of problematic processes
- Process Management: Terminating entire process groups
- Security Analysis: Detecting suspicious process spawning patterns
- Performance Optimization: Understanding application architecture
Basic pstree Command Usage
Simple pstree Execution
The most basic usage of `pstree` displays all processes in a tree format:
```bash
pstree
```
This command produces output similar to:
```
systemd─┬─NetworkManager───2*[{NetworkManager}]
├─accounts-daemon───2*[{accounts-daemon}]
├─acpid
├─atd
├─avahi-daemon───avahi-daemon
├─bluetoothd
├─cron
└─systemd-logind
```
Understanding the Tree Structure
The tree structure uses special characters to show relationships:
- `─` (horizontal line): connects parent to child
- `├─` (branch): indicates a child process with siblings below
- `└─` (end branch): indicates the last child in a group
- `┬─` (T-junction): indicates a parent with multiple children
- `*[process]`: indicates multiple instances of the same process
Using pstree -p for Process IDs
Basic pstree -p Usage
The `-p` option adds process IDs to the display, making it much more useful for system administration:
```bash
pstree -p
```
Sample output with PIDs:
```
systemd(1)─┬─NetworkManager(1234)─┬─{NetworkManager}(1235)
│ └─{NetworkManager}(1236)
├─accounts-daemon(1456)─┬─{accounts-daemon}(1457)
│ └─{accounts-daemon}(1458)
├─acpid(1678)
├─atd(1789)
├─avahi-daemon(1890)───avahi-daemon(1891)
├─bluetoothd(1992)
├─cron(2093)
└─systemd-logind(2194)
```
Focusing on Specific Processes
You can focus the tree on a specific process by providing its PID or name:
```bash
Show tree for a specific PID
pstree -p 1234
Show tree for a specific process name
pstree -p NetworkManager
```
Showing Only User Processes
To display processes for a specific user:
```bash
Show processes for current user
pstree -p $USER
Show processes for specific user
pstree -p username
```
Advanced pstree Options and Examples
Combining Multiple Options
The `pstree` command offers numerous options that can be combined with `-p`:
Show Command Line Arguments (-a)
```bash
pstree -ap
```
This displays full command lines with arguments and PIDs:
```
systemd(1) /sbin/init splash
├─NetworkManager(1234) /usr/sbin/NetworkManager --no-daemon
├─accounts-daemon(1456) /usr/lib/accountsservice/accounts-daemon
```
Show Thread Names (-t)
```bash
pstree -pt
```
This shows individual threads instead of grouping them:
```
systemd(1)─┬─NetworkManager(1234)─┬─{NetworkManager}(1235)
│ ├─{NetworkManager}(1236)
│ └─{gdbus}(1237)
```
Compact Display (-c)
```bash
pstree -pc
```
This disables compaction of identical subtrees, showing all processes individually.
Show Process Groups (-g)
```bash
pstree -pg
```
This includes process group IDs in parentheses alongside PIDs.
Filtering and Sorting Options
Hide Threads (-H)
```bash
pstree -pH
```
This hides threads, showing only processes with their PIDs.
Sort by PID (-n)
```bash
pstree -pn
```
This sorts processes numerically by PID instead of by name.
Show Only Processes with Children (-s)
```bash
pstree -ps init
```
This shows only the path from the specified process to the root, highlighting parent-child relationships.
Practical Use Cases
System Administration Tasks
Monitoring System Services
```bash
Check systemd services and their children
pstree -p systemd
Monitor specific service trees
pstree -p nginx
pstree -p apache2
```
Identifying Resource Usage Patterns
```bash
Show full command lines to identify resource-heavy processes
pstree -ap | grep -E "(java|python|node)"
```
Process Group Management
```bash
Find all processes in a specific user's session
pstree -p username
Identify processes to terminate as a group
pstree -pg $(pgrep firefox)
```
Development and Debugging
Debugging Application Startup
```bash
Monitor how an application spawns child processes
pstree -ap myapplication &
watch -n 1 'pstree -p myapplication'
```
Analyzing Fork Bombs or Runaway Processes
```bash
Identify processes creating too many children
pstree -p | grep -A 5 -B 5 "many_children_process"
```
Container and Virtualization Monitoring
```bash
Monitor Docker container processes
pstree -p $(docker inspect --format '{{.State.Pid}}' container_name)
Check virtual machine processes
pstree -p qemu
```
Security Analysis
Detecting Suspicious Process Trees
```bash
Look for unusual parent-child relationships
pstree -ap | grep -E "(sh|bash|cmd)" | head -20
Monitor processes spawned by web servers
pstree -p apache2
pstree -p nginx
```
Investigating Process Injection
```bash
Check for processes with unexpected parents
pstree -ps suspicious_pid
```
Troubleshooting Common Issues
pstree Command Not Found
Problem: The system returns "command not found" when running `pstree`.
Solution:
1. Install the `psmisc` package:
```bash
# Ubuntu/Debian
sudo apt-get install psmisc
# CentOS/RHEL
sudo yum install psmisc
# Fedora
sudo dnf install psmisc
```
2. Verify installation:
```bash
which pstree
pstree --version
```
Permission Denied Errors
Problem: Cannot view certain processes due to permission restrictions.
Solution:
1. Run with elevated privileges for system-wide visibility:
```bash
sudo pstree -p
```
2. Use alternative approaches for specific processes:
```bash
# View only your own processes
pstree -p $USER
# Use ps command as alternative
ps auxf
```
Truncated or Garbled Output
Problem: Process tree output appears truncated or contains strange characters.
Solution:
1. Adjust terminal width:
```bash
# Set wider terminal
stty cols 120
pstree -p
```
2. Use compact mode:
```bash
pstree -pc
```
3. Redirect to a file for full output:
```bash
pstree -p > process_tree.txt
```
Process Not Showing in Tree
Problem: A known running process doesn't appear in the pstree output.
Solution:
1. Verify the process is running:
```bash
ps aux | grep process_name
```
2. Check if it's a kernel thread:
```bash
pstree -p | grep -E "\[.*\]"
```
3. Use different pstree options:
```bash
pstree -ap | grep process_name
```
Performance Issues with Large Process Trees
Problem: `pstree -p` runs slowly on systems with many processes.
Solution:
1. Focus on specific processes:
```bash
pstree -p specific_process_name
```
2. Use filtering:
```bash
pstree -p | head -50
pstree -p username
```
3. Consider alternatives for large systems:
```bash
ps --forest -eo pid,ppid,user,cmd
```
Best Practices and Tips
Regular Monitoring Strategies
Create Monitoring Scripts
```bash
#!/bin/bash
process_monitor.sh
echo "System Process Tree - $(date)"
echo "================================"
pstree -p | head -30
echo ""
echo "High-Level Process Summary:"
pstree -p | grep -E "systemd|init" -A 5
```
Use Watch for Real-Time Monitoring
```bash
Monitor process tree changes in real-time
watch -n 2 'pstree -p | head -20'
Monitor specific process family
watch -n 1 'pstree -p apache2'
```
Combining with Other Tools
Integration with grep
```bash
Find all Python processes and their trees
pstree -ap | grep python
Find processes with specific arguments
pstree -ap | grep -E "config|conf"
```
Integration with kill Commands
```bash
Find process family before terminating
pstree -p process_name
Then use kill or pkill appropriately
pkill -f process_name
```
Log Analysis
```bash
Save process trees for later analysis
pstree -ap > /var/log/process_tree_$(date +%Y%m%d_%H%M%S).log
Compare process trees over time
diff process_tree_before.log process_tree_after.log
```
Performance Optimization
Efficient Usage Patterns
```bash
Use specific targeting instead of full tree
pstree -p $(pgrep target_process)
Limit output for quick checks
pstree -p | head -n 20
Use compact mode for overview
pstree -pc
```
Resource Considerations
- Avoid running `pstree -ap` frequently on busy systems
- Use targeted queries when possible
- Consider caching output for repeated analysis
- Be mindful of terminal buffer limitations
Security Considerations
Safe Usage Practices
```bash
Always verify process identity before taking action
pstree -ps suspicious_pid
ps -p suspicious_pid -o pid,ppid,cmd,user
Use read-only operations for investigation
pstree -p > investigation.log
```
Avoiding Information Disclosure
- Be cautious when sharing pstree output (may contain sensitive command-line arguments)
- Use `-p` without `-a` when command-line privacy is important
- Consider user-specific queries in multi-user environments
Alternative Tools and Methods
ps Command with Forest View
```bash
Similar tree view using ps
ps --forest -eo pid,ppid,cmd
With user information
ps --forest -eo pid,ppid,user,cmd
```
htop Interactive Process Viewer
```bash
Install and run htop
sudo apt-get install htop
htop
Press F5 for tree view
```
systemd Process Management
```bash
For systemd-based systems
systemctl status --no-pager
systemd-cgls
```
Custom Scripts for Specific Needs
```bash
#!/bin/bash
custom_tree.sh - Enhanced process tree with additional info
pstree -ap | while read line; do
if [[ $line =~ \(([0-9]+)\) ]]; then
pid=${BASH_REMATCH[1]}
mem=$(ps -o rss= -p $pid 2>/dev/null)
echo "$line [MEM: ${mem}KB]"
else
echo "$line"
fi
done
```
Conclusion
The `pstree -p` command is an invaluable tool for understanding and managing process relationships on Unix-like systems. By displaying process trees with their associated PIDs, it provides crucial visibility into system behavior, application architecture, and resource usage patterns.
Key Takeaways
1. Essential System Administration Tool: `pstree -p` offers immediate insight into process hierarchies and relationships
2. Debugging Capability: The combination of tree structure and PIDs makes troubleshooting complex applications more manageable
3. Security Monitoring: Process trees help identify suspicious activities and unauthorized process spawning
4. Performance Analysis: Understanding process families aids in resource optimization and system tuning
5. Flexibility: Multiple options and combinations allow customization for specific monitoring needs
Next Steps
To further enhance your system administration skills:
1. Practice Regular Monitoring: Incorporate `pstree -p` into your daily system monitoring routine
2. Create Custom Scripts: Develop automated monitoring solutions using pstree output
3. Learn Complementary Tools: Explore `htop`, `ps`, and `systemd-cgls` for comprehensive process management
4. Study System Behavior: Use process trees to understand how different applications and services interact
5. Develop Troubleshooting Workflows: Create systematic approaches using pstree for common issues
Final Recommendations
- Always verify process information before taking administrative actions
- Combine `pstree -p` with other monitoring tools for comprehensive system oversight
- Document interesting process patterns for future reference
- Stay updated with system-specific variations and new features
- Practice safe process management techniques to avoid system disruption
By mastering the `pstree -p` command and incorporating it into your toolkit, you'll gain deeper insights into system behavior and become more effective at managing complex Unix/Linux environments. The hierarchical view of processes with their PIDs provides the foundation for advanced system administration, debugging, and security analysis tasks.