Linux offers a robust array of tools designed for managing and monitoring running processes in linux, from foundational commands like ps and top to sophisticated utilities like htop, lsof, strace, and atop. Learning these commands enables users and system administrators to optimize performance, troubleshoot issues, and maintain system security.
In this guide, I will explain all about basic Linux commands and advanced tools on how to monitor the processes running on Linux and how to administer the Linux system better using the best practices.
1. Commands for Viewing Processes in Linux
1.1 Using The ps Command
The ps command is able to list active processes in Linux and show information related to process ID (PID), CPU usage, memory consumed, and command that starts each process; this is particularly useful for making one-time checks or for scripts.
Common Flags for ps
- ps -e: The ps -e command in Linux provides a comprehensive overview of all processes currently running on the system. By using the -e flag, ps retrieves a list of every active process, regardless of the user who initiated it and displays essential details like the Process ID (PID), terminal associated with the process (TTY), CPU time consumed (TIME), and the command that started the process (CMD). This command is especially useful for administrators and developers who need a quick snapshot of system activity across all users. For more detailed insights, additional flags can be combined with ps -e to show memory usage, parent processes, or CPU consumption.
- ps aux: The ps aux command in Linux is a powerful tool for viewing detailed information about all running processes. This command provides a more comprehensive output than ps -e, showing not only the Process ID (PID) and command (CMD) that initiated each process but also the user who started it (USER), the percentage of CPU (%CPU) and memory (%MEM) each process is using, and the process start time (START). This level of detail is valuable for monitoring resource usage, as it allows administrators to identify processes that are consuming high CPU or memory. The ps aux output is commonly used for performance tuning and troubleshooting system issues.
- ps -ef: Linux has a powerful command in the form of ps -ef, which lists all the processes on your system in a full structure format, including PID, parent PID, and the full command (CMD), with which you initiated the process. This format is very useful if you want to see the hierarchy of processes through the relationship between a parent and child. When you can identify the PPID, you can see which other processes started yours; ps -ef is useful for diagnosing errors with specific services/applications. If you are an administrator needing to look at how processes relate and how resources are managed, this command is very useful.
Examples of Using ps
Filtering by User:
ps -u [username]
- To see all processes associated with a user, we can use the ps -u [username] in Linux. This command obtains a list of processes started by or running under the specified user’s account by specifying the username. What this output gives you is the process ID (PID), terminal (TTY), CPU time (TIME), and the command that the process was started with (CMD). Process monitoring is rich all the way from foundational commands such as ps and top to advanced utilities such as strace, lsof, and atop in Linux. Each tool provides a particular view into process behavior, system performance, and resource usage for efficient and secured system management. Learning these commands will make sure you can always keep a comfortable, optimized Linux environment.
Filtering by PID:
ps -p [PID]
- With the command ps -p [PID] in Linux, we are able to display the details from a specific process using its Process ID (PID). This command enters the PID, which then comes up with essential information on the selected process about its status, CPU time, memory usage, and the command to start it. This targeted approach is highly useful for monitoring a particular process closely or for troubleshooting issues associated with a single process, like identifying resource-intensive tasks, checking if a process is still active, or investigating unexpected behavior. It simplifies the task of isolating and analyzing specific processes without sifting through a complete list.
Using ps with grep:
ps aux | grep [process_name]
- The ps aux | grep [process_name] command in Linux is a powerful combination that allows you to search for specific processes by name. The ps aux command lists all active processes along with detailed information, while grep [process_name] filters this list to show only those that match the specified process name. It is especially useful for quickly locating running processes associated with a particular application or service. By isolating processes by name, this method helps in monitoring, managing, and troubleshooting specific tasks, making it easier to identify instances, track resource usage, and verify if a process is running or needs attention.
Additional Tips for ps
- Automating Process Monitoring: You can use ps in scripts for automated monitoring, logging, or alerting. For instance, combining ps with a cron job can enable regular snapshots of high CPU or memory usage.
Combining ps with awk: For advanced filtering, use awk to process ps output. For example, to list only the process name and PID of processes consuming over 10% CPU:
ps aux | awk '$3>10 {print $2, $11}'
1.2 Using the top Command
The top command is a handy tool that offers a live, updating view of processes and resource usage, with data on CPU and memory consumption, process load, and more. top is ideal for real-time monitoring during high system load.
Key Columns in top Output
- PID: Process ID
- USER: User that owns the process
- %CPU: CPU usage percentage, highlighting CPU-intensive processes
- %MEM: Memory usage percentage, helping to track memory-hogging processes
- TIME+: Total CPU time consumed by the process, showing long-running tasks
Advanced Options in top
- Sorting: By default, top sorts by CPU usage, but you can press O to change the sort column.
- Adjusting Refresh Rate: Press d to adjust the refresh interval, which is useful for more or less frequent updates.
- Killing Processes: Press k and enter a PID to terminate a process directly from within top.
Making top Persistent with batch Mode
If you want to log top output over time, you can run it in “batch” mode:
top -b -n 1 > top_output.txt
These logs a single snapshot of the top to a file, which is useful for performance analysis or tracking issues over time.
2. Enhanced Process Management Tools
2.1 Using htop for Interactive Monitoring
It’s an interactive and, in many ways, visually enhanced version of the top, which shows color-coded output and user-friendly navigation in the htop. It is especially useful for detecting resource processes and watching process hierarchy in real-time.
To install htop, run:
sudo apt install htop
Key Features of htop
- Color-Coding: Visual indicators for CPU, memory, and swap usage, making resource-heavy processes stand out.
- Tree View: Displays processes in a hierarchical format, showing parent-child relationships.
- Filtering and Searching: Press / to search for processes by name or PID.
- Sorting and Customizing Columns: Use arrow keys to navigate, F6 to change sorting, and F2 to customize displayed columns.
Advanced Tips for Using htop
- Inspecting Open Files: Select a process, press l, and htop will show a list of open files for that process, useful for diagnosing file locks or I/O bottlenecks.
- Using Filters: Press F3 to filter processes by name or part of the command, narrowing down the list to specific processes.
2.2 Using pgrep and pkill for Process Identification and Termination
pgrep and pkill allow you to locate and terminate processes by name, a convenient alternative to finding PIDs.
pgrep Command
If you’re running Linux, the pgrep command is a handy way to find out the process IDs (PIDs) of processes with a specific name. By using it,
pgrep [process_name]
You can quickly verify all instances of a process without manually filtering through a full list of running processes. It is particularly helpful when managing or troubleshooting multiple instances of the same process.
- Returns the PID(s) of all processes matching the specified name.
pkill Command
The pkill command will terminate processes based on their name without needing to know the exact PID. This command is especially convenient when you need to stop all instances of a particular process.
Killing by Name:
pkill [process_name]
Ends all instances of the specified process. Add the -9 flag to terminate processes forcefully:
pkill -9 [process_name]
3. Advanced Process Inspection and Debugging Tools
3.1 Using lsof to Monitor Open Files and Network Connections
lsof (List Open Files) shows open files and network connections per process, which is invaluable for tracking file handles or diagnosing network activity.
Common Uses of lsof
Listing Open Files by Process:
lsof -p [PID]
- Displays all files opened by a specific process, useful for analyzing file-access issues.
Finding Network Connections:
The lsof -i command is used to display a list of active network connections, which is essential for monitoring network-heavy applications or detecting suspicious activity. This command shows details such as the process ID (PID), user, file descriptor, and network connection type (e.g., TCP or UDP). It’s particularly useful for identifying processes that are currently listening on a network port or actively transmitting data.
lsof -i
- Shows processes with active network connections, ideal for identifying network-heavy applications or suspicious activity.
Filtering by User:
For filtering by user, the lsof -u [username] command is effective. It displays files opened by a specific user, helping administrators monitor user-specific activities or troubleshoot resource usage by individual users.
lsof -u [username]
- Displays files opened by a specific user, helping track user-level resource consumption.
3.2 Using strace for Tracing System Calls
strace is an advanced debugging tool for tracing system calls made by a process, helping diagnose issues by showing how a process interacts with the operating system.
Common strace Commands
Tracing a New Process:
strace -c [command]
- Runs a command and tracks all system calls it makes, providing a summary at the end.
Tracing an Existing Process:
The strace -p [PID] command is used to attach to a running process by its Process ID (PID) and watch in real-time exactly what the system calls it makes. This command is helpful for debugging as it allows you to see what system calls a process performs. It can be used to solve issues with process behavior or the operating system.
strace -p [PID]
- Attaches to an existing process and observes its system calls in real time.
Filtering for Specific System Calls:
strace -e trace=open,close [command]
- Limits output to specific system calls, such as open and close, to focus on file-access operations.
4. Monitoring Network and Socket Activity
4.1 Using netstat and ss Commands for Network Monitoring
netstat and ss commands provide valuable insight into network connections and socket activity on your system.
netstat Command
netstat shows active network connections and their associated processes.
List Active Network Connections:
netstat -tulpn
- Displays all active TCP and UDP connections with associated process IDs (-p flag).
ss Command
ss is a faster, more efficient alternative to netstat, providing similar output with additional filtering options.
Basic Usage of ss:
ss -tulnp
- Lists listening and established connections, along with the PID and program name.
Filtering by Protocol:
ss -tn
- Displays only TCP connections, helping narrow down network activity by protocol.
5. Advanced Service and System Process Management
5.1 Using systemd Utilities for Service Management
Systemd-based systems basically use systemctl and systemd-cgls to manage and view system services and system processes.
systemctl Command
systemctl controls and monitors services, allowing you to start, stop, and check the status of system services.
Checking Service Status:
systemctl status [service_name]
- Provides the current status of a service, including recent logs and active/inactive state.
Starting and Stopping Services:
systemctl start [service_name]
systemctl stop [service_name]
- systemd-cgls Command
systemd-cgls list control groups and active processes in a hierarchical view.
Viewing Process Hierarchy:
systemd-cgls
- Shows active processes organized by the control group, displaying the structure of system processes.
5.2 Using atop for Comprehensive Resource Tracking
Powerful performance monitoring tool atop gives you real-time and historical data on system resource usage (CPU, memory, network, etc) for long-term analysis.
To install atop, use:
sudo apt install atop
Key Features of atop
- Real-Time and Historical Monitoring: It shows current and historical data of system resource usage.
- Detailed Metrics: Shows the usage of CPU, memory, disk, and network with a timestamp for a look back.
- Logging: Records process data at intervals, allowing for historical review even after reboots.
Basic Usage of atop
To start atop in real-time mode, enter:
atop
Navigating atop
- Press m: On top, it displays memory-specific metrics so you can monitor an active process’s memory usage. This view shows detailed statistics on memory allocation, swap usage, and memory load. It allows you to see which processes are consuming the most memory in order to manage your system’s resources better.
- Press d: Detailed view of the disk usage, such as switches above for specific metrics of disk I/O for each process. Including read and write activity, disk load, and individual disk access patterns, it enables you to track which processes are consuming disk resources heavily. It is a particularly useful view in case an I/O bound process may impact the system’s overall performance.
- Press n: It displays Network activity by process atop, showing sent and received data rates, network load, and connection statistics per process. This view provides process-level monitoring of network usage, allowing you to see which applications are using the most bandwidth—and if it’s an indication of a network bottleneck that’s affecting system performance.
- Press c: Pesents CPU usage metrics atop, providing a deep view of broken processes at CPU consumption. CPU load per process, including a percentage of CPU resources used by each process, is shown in this mode. It helps identify processes with high CPU usage, making it easier to manage or troubleshoot CPU-intensive tasks and balance system performance effectively.
Viewing Historical Logs with atop
atop logs to /var/log/atop/. To review a log from a specific date:
atop -r /var/log/atop/atop_YYYYMMDD
Replace YYYYMMDD with the desired date. Navigate timestamps using the t and T keys.
6. Additional Tips and Best Practices for Linux Process Management
- Use Caution with kill -9: Avoid force-killing (kill -9) as it can cause data loss. Use it only for truly unresponsive processes.
- Automate Regular Monitoring: Schedule ps or top snapshots with cron for regular logging and performance tracking.
- Limit Resource Usage with ulimit: Use ulimit to control the usage of some system resources for some processes to prevent some processes from using excessive system resources.
- Monitor for Suspicious Activity: Regularly check for unknown processes with high CPU or network usage to identify potential threats.
Conclusion
Process monitoring is rich all the way from foundational commands such as ps and top to advanced utilities such as strace, lsof, and atop in Linux. Each tool provides a particular view into process behavior, system performance, and resource usage for efficient and secured system management. Learning these commands will make sure you can always keep a comfortable, optimized Linux environment.
About the writer
This article was written by Vinayak Baranwal, For more insightful content or collaboration opportunities, feel free to connect with Vinayak on LinkedIn through the provided link.