CodeBlanks Logo Icon CodeBlanks

Summary - Signal handling

Combine sigaction, kill and safety to write a signal catcher.

Signal catcher

In this group you learned the basics of signals: the signal concept, handlers with signal and sigaction, sending with kill, and signal safety. Together they build a safe signal system.

Now you will combine them into a signal catcher: install a handler with sigaction, send a signal to yourself with kill, and check the result with a volatile sig_atomic_t flag. This pattern is common in background servers.

Practice Signal catcher

Declare volatile sig_atomic_t flag = 0; and void handler(int sig) with flag = 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 kill(getpid(), SIGUSR1); and 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 sigaction struct
// kill and print

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) {
    struct sigaction sa;
    sa.sa_handler = handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGUSR1, &sa, NULL);
    kill(getpid(), SIGUSR1);
    printf("flag=%d\n", flag);
    return 0;
}

Expected output

flag=1

Next steps

You learned signal handling. In the next groups you will see concurrent work with threads and network communication with sockets.

Signals are considered alongside threads: which thread does a signal interrupt? You install a process-wide handler with sigaction. In sockets, a broken connection can be reported via a signal. SIGPIPE reports a write error, SIGIO reports ready data.

Questions and answers

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

1 Which trio builds a safe signal system?

  • signal, fork, exec
  • sigaction, kill, sig_atomic_t Correct answer
  • printf, malloc, free
  • open, read, write

Explanation: sigaction, kill and sig_atomic_t build a safe system.

2 Match system components

Term Meaning
sigaction Installs handler
kill Sends signal
sig_atomic_t Safe flag
raise Signal to self

All lessons in Advanced