0
0
CConceptBeginner · 3 min read

What is Signal Handling in C: Explanation and Example

In C, signal handling is a way for a program to catch and respond to asynchronous events called signals, like interrupts or errors. It lets the program run special functions called signal handlers when these events happen.
⚙️

How It Works

Signal handling in C works like a phone call interrupting your work. Imagine you are writing a letter, and suddenly the phone rings. You stop writing and answer the call. Similarly, a signal is like that phone call sent to your program by the operating system or another program.

When a signal arrives, the program pauses its current task and runs a special function called a signal handler. This handler decides what to do next, like cleaning up resources or saving data before the program stops or continues.

This mechanism helps programs respond quickly to unexpected events such as pressing Ctrl+C, division by zero, or timer expirations.

💻

Example

This example shows how to catch the Ctrl+C interrupt (SIGINT) and print a message instead of immediately stopping the program.

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

void handle_sigint(int sig) {
    printf("\nCaught signal %d (Ctrl+C). Program will continue.\n", sig);
}

int main() {
    signal(SIGINT, handle_sigint);  // Set the signal handler
    printf("Press Ctrl+C to test signal handling.\n");
    while (1) {
        sleep(1);  // Wait here
    }
    return 0;
}
Output
Press Ctrl+C to test signal handling. Caught signal 2 (Ctrl+C). Program will continue. Caught signal 2 (Ctrl+C). Program will continue. ...
🎯

When to Use

Use signal handling when your program needs to react to unexpected or external events without crashing immediately. For example:

  • Gracefully stopping a program when the user presses Ctrl+C.
  • Handling errors like division by zero or invalid memory access.
  • Responding to timer events or alarms.
  • Cleaning up resources before exiting after receiving a termination signal.

This helps make programs more robust and user-friendly.

Key Points

  • Signals are asynchronous notifications sent to a program.
  • Signal handlers are special functions that run when a signal occurs.
  • Common signals include SIGINT (Ctrl+C), SIGTERM (termination), and SIGFPE (arithmetic errors).
  • Signal handling allows programs to manage interruptions and errors gracefully.

Key Takeaways

Signal handling lets C programs respond to asynchronous events like interrupts or errors.
A signal handler is a function that runs automatically when a specific signal occurs.
Use signal handling to clean up or control program behavior on events like Ctrl+C or errors.
Common signals include SIGINT for interrupts and SIGTERM for termination requests.
Proper signal handling makes programs more stable and user-friendly.