CodeBlanks Logo Icon CodeBlanks

Signal safety

Learn signal safety and reentrant functions.

Signal safety

A signal handler can interrupt the program at any point. So inside a handler you should only call reentrant functions.

Functions like malloc, printf, fopen are not reentrant; they hold internal static state. In a handler, write and _exit are safe. For a flag variable you use volatile sig_atomic_t; its read and write are indivisible.

volatile sig_atomic_t

volatile tells the compiler to read the variable from memory on every access without optimization. sig_atomic_t is a type guaranteed to have indivisible read and write.

The handler sets a flag; the main loop checks the flag and reacts. This is the core pattern of safe signal communication. For example, declare volatile sig_atomic_t flag = 0; and set flag = 1; in the handler. The main code waits with while (!flag).

Practice Safe flag

Declare volatile sig_atomic_t flag = 0;. Write void handler(int sig) with flag = 1;. Register with signal(SIGUSR1, handler);. Call raise(SIGUSR1); and print with printf("flag=%d\n", flag);.

Starter code

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

// Define flag variable
// Write handler
// Register with signal, raise
// Print flag

int main(void) {
    return 0;
}

Sample solution

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

volatile sig_atomic_t flag = 0;

void handler(int sig) {
    flag = 1;
}

int main(void) {
    signal(SIGUSR1, handler);
    raise(SIGUSR1);
    printf("flag=%d\n", flag);
    return 0;
}

Expected output

flag=1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match safety concepts

Term Meaning
volatile Prevents optimization
sig_atomic_t Indivisible type
write Safe function
malloc Not safe

2 Which function is safe in a signal handler?

  • write Correct answer
  • printf
  • malloc
  • fopen

Explanation: write is a reentrant system call.

3 Flag type

Question
volatile ____ flag = 0;
Answer
volatile sig_atomic_t flag = 0;

Explanation: sig_atomic_t is used for indivisible flags in handlers.

All lessons in Advanced