Basic Process Management in Linux

Master the essentials of Linux process management! This guide introduces you to key commands like ps, top, kill, and htop to monitor, find, and terminate processes effectively. We’ll also walk through a practical shell script to monitor CPU usage of a specific process, empowering you to take full control of your Linux environment.

Hey everyone, and welcome to a crucial deep dive for anyone working with Linux: process management. Whether you’re a budding software engineer, an IT professional, or just an enthusiast managing your own system, understanding processes is fundamental. Think of processes as the beating heart of your Linux machine – every application you run, every command you execute, is a process. Being able to monitor, manage, and troubleshoot these processes is key to maintaining a healthy, performant, and stable system.

In this post, we’ll journey through the most essential commands: ps for static snapshots, top and htop for real-time monitoring, and kill for terminating misbehaving tasks. To make this learning truly hands-on, we’ve prepared a practical demonstration involving a custom script to monitor CPU usage. Let’s get started and take control of your Linux environment!

What is a Process?

Before we dive into the commands, let’s briefly clarify what a process is. In Linux (and other operating systems), a process is an instance of a running program. It’s a fundamental unit of work, encompassing the program code, its data, system resources (like open files, network connections), and its execution state. Every command you type into your terminal launches at least one process, and often many more are running in the background, managed by the operating system.

1. The ps Command: Your Static Snapshot

First up is the ps command, short for “process status.” Unlike some of the other tools we’ll explore, ps gives you a static snapshot of the processes currently running on your system. Imagine taking a photograph of all the activity at a precise moment – it’s not real-time, but it’s incredibly useful for quickly seeing what’s happening.

Common Usages of ps:

  • ps aux: A Broad Overview
    This is one of the most common and powerful ways to use ps.

    • a: Shows processes for all users.
    • u: Displays user/owner and other detailed information.
    • x: Shows processes not attached to a terminal.

    This gives you a broad overview, showing things like PID (Process ID), CPU and memory usage, start time, and the command that launched the process.

    ps aux
  • ps -ef: Full Format Listing
    Another popular way to display all processes, often preferred for its clear display of the process hierarchy and parent-child relationships.

    • e: Selects all processes.
    • f: Does a full-format listing.
    ps -ef
  • Finding Specific Processes with grep
    Viewing all processes is great, but what if you’re looking for something specific? This is where the power of pipes (|) and grep comes in. grep is a command-line utility for searching text. By piping the output of ps aux (or ps -ef) to grep, you can filter the results.

    ps aux | grep chrome

    Pro-Tip: To prevent grep from matching its own process in the output (which can clutter results), you can use square brackets around the first letter of your search term:

    ps aux | grep [c]hrome

    This combination is your go-to method for quickly locating a rogue process or confirming if an application is running.

2. The top Command: Your Live Dashboard

While ps gives you a static view, top provides a real-time, dynamic display of your running system. Imagine watching a live dashboard rather than looking at a photograph. When you launch top, you’ll see a summary of system information at the top (uptime, load averages, task summaries) followed by a list of processes sorted by CPU usage by default. It updates every few seconds, allowing you to observe how CPU and memory usage fluctuate.

top

Interactive Features of top:

top isn’t just a viewer; it’s also interactive:

  • Press k: To kill a process. It will prompt you for the PID and then ask for a signal to send (default is SIGTERM).
  • Press r: To renice a process, changing its priority and influencing how much CPU time it gets.
  • Press q: To quit top and return to your terminal prompt.

Understanding these interactive commands can significantly speed up your diagnostics and management tasks directly within the top interface.

3. The htop Command: An Enhanced Experience

While top is powerful, htop takes process management to the next level. htop is an enhanced, interactive process viewer that offers a more user-friendly interface than top. It’s often not installed by default, but it’s a must-have for many Linux users.

Installation:

You can install htop easily on most distributions:

  • Debian/Ubuntu:
    sudo apt install htop
  • Fedora/RHEL/CentOS:
    sudo dnf install htop

Once installed, just type htop to launch it. You’ll immediately notice the difference: a colorful interface, clear meters for CPU and memory usage across all cores, and an intuitive layout.

htop

Key Features of htop:

  • Intuitive Interface: Colorful, easy-to-read meters for CPU and memory usage.
  • Mouse Support: Click to select processes, scroll, and interact.
  • Function Keys for Quick Actions:
    • F3: Search for a process.
    • F4: Filter the displayed processes.
    • F5: Toggle tree view, which graphically displays parent-child relationships.
    • F9: Send signals and kill a selected process with just a few keystrokes.
  • Vertical & Horizontal Scrolling: Navigate long lists of processes and see full command lines.

These features combine to make htop an incredibly efficient tool for detailed process inspection and management.

4. The kill Command: Terminating Processes

Eventually, you’ll encounter a process that needs to be stopped. This is where the kill command comes in. kill is used to send signals to processes. The most common use is to terminate them.

Understanding Signals:

  • kill [PID] (SIGTERM, Signal 15):
    This sends a SIGTERM (signal 15), which is a polite request for the process to shut down. This allows the process to perform any cleanup operations (like saving data, closing files) before exiting. It’s the preferred method for termination.

    kill 12345

    (Replace 12345 with the actual Process ID)

  • kill -9 [PID] (SIGKILL, Signal 9):
    If a process is truly stuck and unresponsive, you might need to use kill -9 [PID]. This sends a SIGKILL (signal 9), which is a forceful, immediate termination that cannot be ignored by the process.

    Caution: Use kill -9 with caution, as it prevents the process from cleaning up, potentially leading to data corruption or orphaned resources. It’s considered the “last resort.”

    kill -9 12345
  • killall [process_name]:
    For quickly terminating all instances of an application by name, killall [process_name] is a handy alternative.

    killall firefox

Putting It Into Practice: Hands-On Process Management

To make this practical, we’ve prepared a small project for you. In the accompanying GitHub repository, you’ll find two simple shell scripts: dummy_process.sh and monitor_cpu_usage.sh.

  • dummy_process.sh: Designed to run indefinitely, consuming some CPU cycles, so we have a target for our monitoring and termination exercises.
  • monitor_cpu_usage.sh: Designed to continuously fetch and display the CPU utilization of a specified process.

Step-by-Step Guide:

  1. Clone the Repository:
    git clone https://github.com/aicoresynapseai/code.git
  2. Navigate to the Scripts Directory:
    cd code/LinuxProcessExplorer/scripts
  3. Make Scripts Executable:
    chmod +x dummy_process.sh monitor_cpu_usage.sh
  4. Start the Dummy Process in the Background:

    The ampersand (&) is crucial; it detaches the process from your current terminal, allowing you to continue working while it runs. Pay close attention to the PID that the script prints – we’ll need that for the next step.

    ./dummy_process.sh &

    You’ll see output like: Dummy process started. PID: 12345

  5. Monitor CPU Usage of the Dummy Process:

    You can provide monitor_cpu_usage.sh with either the PID you noted earlier or the process name:

    # Monitor by PID (replace 12345 with your actual PID)
    ./monitor_cpu_usage.sh 12345
    
    # Or monitor by process name
    ./monitor_cpu_usage.sh dummy_process.sh

    Internally, this script leverages the ps -p [PID] -o %cpu command to extract the CPU usage percentage. It then prints the timestamp and CPU usage every two seconds, giving you a live feed. Press Ctrl+C to stop the monitoring script.

  6. Observe with top and htop:

    Open a new terminal and run top or htop. You should clearly see dummy_process.sh listed, consuming CPU. Use htop‘s search (F3) or kill (F9) features for practice.

    top
    # or
    htop
  7. Terminate the Dummy Process:

    Once you’re done monitoring, it’s time to terminate our dummy process. First, ensure you have the correct PID (you can use ps aux | grep [d]ummy_process.sh if you’ve forgotten).

    # Terminate gracefully
    kill [PID_of_dummy_process]
    
    # If it doesn't respond (unlikely for this script, but good practice)
    kill -9 [PID_of_dummy_process]

    After issuing the kill command, observe that our monitor_cpu_usage.sh script will eventually report that the process no longer exists, and top or htop will also show that it’s gone from the process list. This confirms successful termination!

Source Code for Reference:

For your convenience, here are the contents of the README and the two shell scripts used in the demonstration. You can find the full, up-to-date source code on the GitHub repository.

LinuxProcessExplorer/README.md

# LinuxProcessExplorer/README.md
This project, "Linux Process Explorer", provides a hands-on introduction to basic process management in Linux. It covers essential commands like `ps`, `top`, `htop`, and `kill` which are crucial for monitoring and managing running processes. Additionally, it includes a custom shell script to demonstrate continuous CPU usage monitoring for a specific process.

Key Concepts and Commands Explained:

1.  ps (Process Status)
    The `ps` command displays information about currently running processes. It's a snapshot of the processes.
    *   `ps aux`: Shows all processes (owned by any user) running on the system, including those not attached to a terminal.
        *   `a`: show processes for all users.
        *   `u`: display user/owner and other detailed information.
        *   `x`: show processes not attached to a terminal.
    *   `ps -ef`: Another common way to display all processes in a full format.
        *   `e`: selects all processes.
        *   `f`: does a full-format listing.
    *   `ps aux | grep [process_name]`: Useful for finding a specific process by its name (or part of its name). The `grep` command filters the output of `ps`.

2.  top (Table of Processes)
    The `top` command provides a real-time, dynamic view of a running system. It shows a summary of system and process information, including CPU usage, memory usage, and a list of the most CPU-intensive tasks.
    *   Interactive usage:
        *   Press `k`: To kill a process (it will prompt for PID and signal).
        *   Press `r`: To renice a process (change its priority).
        *   Press `q`: To quit `top`.

3.  htop (Enhanced top)
    `htop` is an interactive process viewer that is an enhanced alternative to `top`. It offers a more user-friendly interface with features like vertical and horizontal scrolling, mouse support, and clearer visual representation.
    *   Installation: `htop` is often not installed by default. You can install it on Debian/Ubuntu with `sudo apt install htop` or on Fedora/RHEL with `sudo dnf install htop`.
    *   Features: Easy process killing by selecting and pressing F9, tree view, filtering, and more.

4.  kill (Send Signal to Processes)
    The `kill` command is used to send signals to processes. The most common use is to terminate processes.
    *   `kill [PID]`: Sends the SIGTERM (terminate) signal (signal 15). This is a polite request for the process to shut down, allowing it to clean up before exiting.
    *   `kill -9 [PID]`: Sends the SIGKILL (kill) signal (signal 9). This is a forceful termination that cannot be ignored by the process. Use with caution as it doesn't allow the process to perform cleanup.
    *   `killall [process_name]`: Kills all processes with a given name. This is useful when you want to terminate multiple instances of an application.

Project Structure:

*   `scripts/monitor_cpu_usage.sh`: A shell script designed to continuously monitor the CPU usage of a specific process by its PID or name.
*   `scripts/dummy_process.sh`: A simple shell script that runs indefinitely, consuming some CPU, to serve as a target for monitoring and termination exercises.

How to Use This Project:

1.  Navigate to the `scripts` directory:
    cd LinuxProcessExplorer/scripts

2.  Make the scripts executable:
    chmod +x monitor_cpu_usage.sh dummy_process.sh

3.  Start the dummy process in the background:
    ./dummy_process.sh &
    This will start the `dummy_process.sh` and put it into the background, allowing you to continue using your terminal. Note the PID that is printed (e.g., "Dummy process started. PID: 12345").

4.  Find the PID of the dummy process (if you missed it):
    ps aux | grep dummy_process.sh
    Look for a line similar to `/bin/bash ./dummy_process.sh` and identify its PID (the second column).

5.  Monitor the CPU usage of the dummy process:
    You can use its PID:
    ./monitor_cpu_usage.sh [PID_of_dummy_process]
    (Replace `[PID_of_dummy_process]` with the actual PID you found, e.g., `./monitor_cpu_usage.sh 12345`)

    Or, you can use its name:
    ./monitor_cpu_usage.sh dummy_process.sh

    The script will start printing the CPU usage of the dummy process every few seconds. Press `Ctrl+C` to stop the monitoring script.

6.  Experiment with `top` and `htop`:
    Open a new terminal and run:
    top
    Observe the `dummy_process.sh` in the list, its CPU usage, and PID.
    (Press `q` to quit `top`).

    If you have `htop` installed, try:
    htop
    Enjoy the more interactive interface. You can search for `dummy_process.sh` (F3) or kill it directly (F9).
    (Press `F10` or `q` to quit `htop`).

7.  Terminate the dummy process:
    Once you're done monitoring, you can kill the dummy process.
    Using its PID:
    kill [PID_of_dummy_process]
    (e.g., `kill 12345`)

    Verify it's gone:
    ps aux | grep dummy_process.sh
    You should no longer see the dummy process running. The `monitor_cpu_usage.sh` script (if still running) will also report that the process no longer exists.

This project provides a practical foundation for understanding and interacting with processes in a Linux environment.

scripts/dummy_process.sh

#!/bin/bash

# This is a simple dummy process that runs indefinitely.
# It simulates a long-running background task by performing
# some calculations to consume a bit of CPU, then pauses.

echo "Dummy process started. PID: $$"
echo "To terminate this process, use 'kill $$' or 'killall dummy_process.sh'."
echo "To put it in the background, run it as './dummy_process.sh &'."
echo "To monitor its CPU usage, use './monitor_cpu_usage.sh $$' or './monitor_cpu_usage.sh dummy_process.sh'"
echo "----------------------------------------------------------"

# Infinite loop to keep the process running until manually terminated
while true; do
    # Perform a CPU-intensive operation.
    # 'seq 1 500000' generates numbers from 1 to 500,000.
    # 'md5sum' calculates the MD5 hash for each number, consuming CPU.
    # '> /dev/null' redirects the output to prevent flooding the terminal.
    # Adjust '500000' to increase/decrease CPU load.
    seq 1 500000 | md5sum > /dev/null

    # Sleep for a short period.
    # This prevents the script from consuming 100% CPU constantly and
    # allows other system processes to run, making monitoring more visible.
    sleep 0.5
done

scripts/monitor_cpu_usage.sh

#!/bin/bash

# This script monitors the CPU usage of a specified process.
# It can take either a Process ID (PID) or a process name as an argument.

# --- Usage check ---
if [ -z "$1" ]; then
    echo "Usage: $0 <PID_or_PROCESS_NAME>"
    echo "Example: $0 12345"
    echo "Example: $0 dummy_process.sh"
    exit 1
fi

PROCESS_IDENTIFIER="$1"
TARGET_PID=""

# --- Determine the target PID ---
# Check if the identifier is purely numeric (assume it's a PID)
if [[ "$PROCESS_IDENTIFIER" =~ ^[0-9]+$ ]]; then
    TARGET_PID="$PROCESS_IDENTIFIER"
    # Verify if the PID actually exists
    if ! ps -p "$TARGET_PID" > /dev/null; then
        echo "Error: Process with PID $TARGET_PID does not exist."
        exit 1
    fi
else
    # Assume it's a process name, try to find PID using pgrep
    # pgrep -f: Search the full command line for the pattern.
    # pgrep -o: Output only the process IDs.
    # head -n 1: In case multiple processes match, take the first one found.
    TARGET_PID=$(pgrep -f "$PROCESS_IDENTIFIER" | head -n 1)

    if [ -z "$TARGET_PID" ]; then
        echo "Error: No process found matching '$PROCESS_IDENTIFIER'."
        echo "Please ensure the process is running and the name is accurate."
        exit 1
    fi
    echo "Found process matching '$PROCESS_IDENTIFIER' with PID: $TARGET_PID. Monitoring..."
fi

echo "Monitoring CPU usage for PID: $TARGET_PID. Press Ctrl+C to stop."
echo "---------------------------------------------------------"

# --- Monitoring Loop ---
# Loop indefinitely to continuously fetch and display CPU usage
while true; do
    # Check if the process still exists before attempting to get its stats.
    # This prevents errors if the process is terminated while monitoring.
    if ! ps -p "$TARGET_PID" > /dev/null; then
        echo "Process with PID $TARGET_PID no longer exists. Exiting monitor."
        break # Exit the loop if the process is gone
    fi

    # Get CPU usage using the 'ps' command.
    # 'ps -p $TARGET_PID': Focus on the specific process ID.
    # '-o %cpu': Output only the CPU usage percentage.
    # 'tail -n 1': Get the last line (actual CPU value, skipping header).
    # 'xargs': Trim any leading/trailing whitespace.
    CPU_USAGE=$(ps -p "$TARGET_PID" -o %cpu | tail -n 1 | xargs)

    # Get the current timestamp for logging purposes.
    TIMESTAMP=$(date +'%Y-%m-%d %H:%M:%S')

    # Print the monitoring data to the console.
    echo "[$TIMESTAMP] PID: $TARGET_PID, CPU: ${CPU_USAGE}%"

    # Wait for a few seconds before the next check.
    # This interval can be adjusted to change the monitoring frequency.
    sleep 2
done

Watch the Video Tutorial

Prefer a visual walkthrough? This blog post is designed to complement our detailed YouTube video tutorial. Watch it here for a step-by-step demonstration and further explanations:

Explore the Code on GitHub

All the scripts and a comprehensive README are available on our GitHub repository. Feel free to clone the project, experiment with the code, and even contribute!

Conclusion

And there you have it! A comprehensive overview of basic process management in Linux. We’ve explored how to get a snapshot of processes with ps and its powerful filtering capabilities with grep. We then moved into the dynamic world of top and its enhanced counterpart, htop, for real-time monitoring and interactive management. Finally, we learned how to gracefully and forcefully terminate processes with kill and even built a custom script to monitor CPU usage.

Mastering these tools will give you immense control and insight into your Linux systems, empowering you to troubleshoot, optimize, and maintain stable environments. Keep experimenting with these commands, and soon they’ll become second nature.

If you found this blog post and the accompanying video helpful, please give it a thumbs up, share it with your fellow engineers and students, and don’t forget to subscribe to our channel for more in-depth technical tutorials. Your support helps us create more valuable content for the community. Thanks for reading, and happy Linux-ing!

Posted in

Leave a Reply

Discover more from Modern Java developement with Devops and AI

Subscribe now to keep reading and get access to the full archive.

Continue reading