CodeBlanks Logo Icon CodeBlanks

sigaction

Learn advanced signal handling with sigaction.

The sigaction structure

sigaction is the modern, portable alternative to signal. With the struct sigaction you specify handler, mask and flags separately.

First declare struct sigaction sa;. Assign the handler with sa.sa_handler = handler;. Empty the mask with sigemptyset(&sa.sa_mask). Reset flags with sa.sa_flags = 0;. Then register with sigaction(SIGUSR1, &sa, NULL). This is more controlled and safer than signal.

sa_flags and mask

sa_flags changes the handler behavior. SA_RESTART automatically restarts interrupted system calls. SA_SIGINFO passes extra info to the handler.

sa_mask is the set of signals blocked while the handler runs. With sigemptyset no other signal is blocked during the handler. You can add specific signals with sigaddset. This control is not available in signal.

Practice Catch with sigaction

Define int caught = 0; and void handler(int sig) with caught = 1;. Declare struct sigaction sa;; set sa.sa_handler = handler;, sigemptyset(&sa.sa_mask);, sa.sa_flags = 0;. Register with sigaction(SIGUSR1, &sa, NULL);. Call raise(SIGUSR1); and printf("caught=%d\n", caught);.

Starter code

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

int caught = 0;

// Write handler function
// Declare sigaction struct
// Register and raise

int main(void) {
    return 0;
}

Sample solution

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

int caught = 0;

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

int main(void) {
    struct sigaction sa;
    sa.sa_handler = handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGUSR1, &sa, NULL);
    raise(SIGUSR1);
    printf("caught=%d\n", caught);
    return 0;
}

Expected output

caught=1

Questions and answers

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

1 sa_handler assignment

Question
sa.sa_handler = ____;
Answer
sa.sa_handler = handler;

Explanation: sa_handler is assigned the handler function.

2 Match sigaction fields

Term Meaning
sigaction Modern handler
sa_handler Handler field
sa_flags Flags field
sigemptyset Empty mask

3 What advantage does sigaction have over signal?

  • It is faster
  • Requires less code
  • More controlled and portable Correct answer
  • Changes the signal number

Explanation: sigaction is more controlled and consistent across systems.

All lessons in Advanced