Course contentsShow
← C
Lesson 838 of 1,21911. The Preprocessor and BuildFree lesson

Attaching GDB to a running process

Attaching GDB to a running process

What you'll learn: How to jump into the middle of a live, running C program to debug it without restarting the process.

The "Fixing a moving car" analogy

Imagine you’re a mechanic. Usually, you work on a car while it’s parked in your garage (starting a program inside GDB). But sometimes, a car only makes a strange rattling noise when it's cruising at 60 mph on the highway. You can’t ask the driver to stop and restart, or the noise might disappear. Instead, you need to "hop into" the passenger seat while the car is already moving to see what's wrong.

Attaching GDB to a running process is exactly like that. It allows you to inspect a program that is already executing—perhaps a long-running server or a background task—without killing it and starting over.

Step 1: Find the Process ID (PID)

Every running program on your computer is assigned a unique number called a Process ID (PID). Before you can attach GDB, you need to find this number. You can use the ps command in your terminal:

ps aux | grep my_program

Look for the number in the second column. Let's say your program's PID is 1234.

Step 2: The Handshake

Now, you tell GDB to take control of that specific process. You can do this from inside GDB or directly from the terminal.

From the terminal:

gdb -p 1234

From inside GDB:

(gdb) attach 1234

What happens next?

The moment GDB attaches, it sends a signal to the program to pause. Your program will freeze in its tracks. This is your chance to set breakpoints, look at variables, or check the backtrace to see exactly which function is currently executing.

// Example: A program you might need to attach to
#include <stdio.h>
#include <unistd.h>

int main() {
    int counter = 0;
    while(1) {
        // Imagine this program is running in the background
        // and you want to see what 'counter' is right now.
        printf("Processing data... %d\n", counter++);
        sleep(2); 
    }
    return 0;
}

When you are done, use the detach command. This "hops out" of the car and lets the program continue running at full speed again.

Key takeaway

Use gdb -p <PID> to hijack a running process, allowing you to debug live issues without restarting the software.