Course contentsShow
← C
Lesson 1088 of 1,21915. Systems ProgrammingFree lesson

The sigaction struct and function

The sigaction struct and function

What you'll learn: How to use the modern, robust way to intercept and handle signals in a C program.

In earlier lessons, you might have seen the signal() function. While simple, signal() is like a flimsy sticky note; it’s unreliable across different versions of Unix and sometimes resets itself after one use. In professional systems programming, we use sigaction. It is the heavy-duty toolkit for defining exactly what should happen when a signal—like a manual interrupt (SIGINT) or a termination request (SIGTERM)—hits your process.

The Recipe: The sigaction struct

Think of the sigaction struct as a set of instructions you leave for the Operating System. It tells the OS: "When this specific signal arrives, use this specific handler, and please ignore these other signals while you're at it."

The struct has three main parts you need to know:

  1. sa_handler: The pointer to your custom function.
  2. sa_mask: A set of signals to block while your handler is running (to prevent "signal overlap").
  3. sa_flags: Special options, like SA_RESTART, which tells the OS to resume interrupted system calls automatically.

Putting it to work

To use it, you create the struct, fill it with your preferences, and pass it to the sigaction() function. Unlike signal(), this configuration stays in place until you manually change it.

#include <stdio.h>
#include <signal.h>
#include <unistd.h>

// Our custom handler function
void handle_interrupt(int sig) {
    printf("\nCaught signal %d! Cleaning up...\n", sig);
}

int main() {
    struct sigaction sa;

    // 1. Point to our handler function
    sa.sa_handler = &handle_interrupt;
    
    // 2. Clear the mask (don't block additional signals)
    sigemptyset(&sa.sa_mask);
    
    // 3. Set flags (restart interrupted system calls)
    sa.sa_flags = SA_RESTART;

    // Apply the settings for SIGINT (Ctrl+C)
    sigaction(SIGINT, &sa, NULL);

    printf("Waiting for Ctrl+C... (Try it!)\n");
    while(1) {
        sleep(1);
    }

    return 0;
}

Why this matters

By using sigaction, you ensure your program behaves predictably. It prevents a second signal from crashing your program while your first signal handler is still trying to clean up files or close connections. It is the gold standard for writing stable, "signal-aware" Linux software.

Key takeaway

The sigaction struct provides a portable and reliable way to define complex signal-handling behavior that won't reset or glitch under pressure.