← GCC/C Index

📡 <signal.h> — Signal Handling

Allows a program to catch or ignore OS signals such as SIGINT (Ctrl+C) and SIGSEGV (segfault).

Include: #include <signal.h> | Compile: gcc -Wall -o prog prog.c

📋 Functions & Macros

NamePrototype / ValueDescription
signalvoid (*signal(int sig, void (*handler)(int)))(int)Install a signal handler
raiseint raise(int sig)Send a signal to the current process
SIGINT2Interrupt (Ctrl+C)
SIGTERM15Termination request
SIGSEGV11Segmentation fault
SIGABRT6Abort signal
SIGFPE8Floating-point exception
SIG_DFL0Default handler
SIG_IGN1Ignore the signal

💡 Example Program

Copy, save as demo.c, and compile with the command shown at the bottom.

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

volatile int keep_running = 1;

void handle_sigint(int sig) {
    (void)sig;
    printf("\nCaught SIGINT. Shutting down...\n");
    keep_running = 0;
}

int main(void) {
    signal(SIGINT, handle_sigint);
    printf("Press Ctrl+C to stop.\n");
    long count = 0;
    while (keep_running) count++;
    printf("Counted to %ld before stopping.\n", count);
    return 0;
}
/* Compile: gcc -Wall -o signal_demo signal_demo.c */

← <assert.h>  |  🏠 Index  |  <unistd.h> →