Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Signal Handling (`signal | C Programming Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 42 of 50

·c

Signal Handling (`signal.h`)

9 mins

Course progress84%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • `signal` is simple but has portability quirks; `sigaction` is the preferred POSIX method.
  • Do **not** call non‑async‑signal‑safe functions (e.g., `printf`) from a signal handler on strict POSIX systems.
  • Use `sigemptyset`/`sigaddset` to control which signals are blocked during handler execution.
  • Handlers can be used for cleanup, graceful shutdown, or to implement timers.

Signals are asynchronous notifications (e.g., SIGINT, SIGTERM). Use signal or the more robust sigaction to install handlers.

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

void handler(int sig) {
    if (sig == SIGINT) {
        printf("
Caught Ctrl‑C, exiting gracefully...
");
        exit(0);
    }
}

int main(void) {
    struct sigaction sa = {0};
    sa.sa_handler = handler;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGINT, &sa, NULL);
    while (1) { /* busy work */ }
    return 0;
}
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from C Programming FundamentalsBrowse activities
Previous lessonPOSIX Threads (`pthread`) – AdvancedContinue to lesson 43File I/O – Binary FilesBack to C Programming Fundamentals curriculum