Course contentsShow
← Linux
Lesson 185 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Process Tree Monitoring

Track the lifecycle of spawned child processes for cleanup tasks.

In this lesson, you will learn how to monitor the lifecycle of spawned child processes to ensure they are properly cleaned up when your main script exits.

When you run a script that kicks off several background tasks, those child processes don't always die when the parent script finishes. If you aren't careful, you end up with "zombie" or "orphan" processes consuming system resources. To manage this, we track the Process Tree—a parent-child hierarchy where every process is linked to the one that started it.

The Problem: Stray Children

Imagine your script starts a long-running background task (like a data processor) using the & operator. If your script finishes or crashes, that background task might keep running indefinitely. To prevent this, you need to monitor the tree so you can send a termination signal to all active descendants before your script exits.

Tracking with pgrep

The easiest way to identify these children is by using their parent process ID (PPID). Every process in Linux knows who its parent is. We can use pgrep to list all processes currently "owned" by our script's process ID:

# Find all child PIDs where the parent is our current script (BASHPID)
CHILD_PIDS=$(pgrep -P $BASHPID)

# Clean them up before exiting
cleanup() {
    echo "Cleaning up processes: $CHILD_PIDS"
    kill $CHILD_PIDS
}

# Ensure cleanup runs on exit
trap cleanup EXIT

# Example: Starting a child process
sleep 100 &

Why This Matters

By capturing the BASHPID (a built-in variable representing your current script's process), you create a anchor point. When your script triggers a trap (an interrupt signal like EXIT or SIGINT), you look back at that anchor to see if any children are still attached. If they are, you send them a SIGTERM signal. This keeps your system clean, prevents memory leaks, and ensures that your automated tasks don't leave a "trail of debris" behind them.

Key Takeaway: You must explicitly track and terminate child processes on script exit, or they will continue to run as orphans, potentially destabilizing your system.