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

Blocking signals with sigprocmask()

Blocking signals with sigprocmask()

What you'll learn: How to temporarily delay signals from interrupting critical sections of your code using a process signal mask.

The "Do Not Disturb" Sign

Imagine you are writing an important letter. If someone taps you on the shoulder to ask a question, you might lose your train of thought. To prevent this, you could put on noise-canceling headphones. You aren't ignoring the world forever; you are just delaying the interruption until you finish your sentence.

In C, sigprocmask() acts like those headphones. It allows your program to "block" specific signals. When a signal is blocked, the operating system doesn't discard it. Instead, it places the signal in a "pending" state. As soon as you unblock it, the signal is delivered and handled.

Using the Signal Mask

To block signals, we use a sigset_t variable to hold a list of signals we want to mask. The sigprocmask() function then applies this list to the process.

It takes three arguments:

  1. How: Usually SIG_BLOCK (to add to the current mask) or SIG_UNBLOCK (to remove).
  2. Set: The list of signals to block or unblock.
  3. Oldset: A place to store the previous mask (useful for restoring settings later).

Example: Protecting a Critical Section

In this example, we block SIGINT (the signal sent by pressing Ctrl+C) while the program performs a "critical" calculation.

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

int main() {
    sigset_t set;
    
    // 1. Initialize the set and add SIGINT
    sigemptyset(&set);
    sigaddset(&set, SIGINT);

    // 2. Block the signal
    printf("Blocking Ctrl+C. Try pressing it now...\n");
    sigprocmask(SIG_BLOCK, &set, NULL);

    // 3. Critical Section
    for(int i = 5; i > 0; i--) {
        printf("Working safely... %d\n", i);
        sleep(1);
    }

    // 4. Unblock the signal
    printf("\nWork finished. Unblocking Ctrl+C...\n");
    sigprocmask(SIG_UNBLOCK, &set, NULL);

    printf("Back to normal. The program will now exit if you pressed Ctrl+C.\n");
    return 0;
}

Why block instead of ignore?

If you ignore a signal, it vanishes. If you block it, the signal is queued. This is vital when your code is mid-calculation or modifying a global variable; you want the signal to happen, just not right this second. Once sigprocmask unblocks the signal, the kernel checks for pending signals and triggers the handler immediately.

Key takeaway

Use sigprocmask() to protect sensitive code from interruptions by putting signals on hold until your work is done.