C Signal Handling

C Signal Handling – Working with Signals in C

In C, signal handling is used to catch signals sent to a program, such as a termination signal or an interrupt. The signal.h library allows you to define custom signal handlers for various system events.

๐Ÿ”น What are Signals?

Signals are notifications sent to a process to notify it of events that require attention. Examples include interruptions, errors, or termination requests. Signals can be sent by the system or other processes.

๐Ÿ“ Syntax for Signal Handling

To handle signals in C, you use the signal() function. The syntax is as follows:

signal(signal_number, signal_handler_function);
  • signal_number: The signal you want to catch (e.g., SIGINT, SIGTERM).
  • signal_handler_function: A function that will handle the signal.

๐Ÿ“ Example 1: Handling SIGINT (Ctrl+C)

This example demonstrates how to catch the SIGINT signal, which is triggered when the user presses Ctrl+C to interrupt the program.

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

void signal_handler(int signal) {
    printf("Caught signal %d: Interrupt signal (SIGINT) received.\n", signal);
    exit(0);  // Exit the program after handling the signal
}

int main() {
    signal(SIGINT, signal_handler);  // Catch SIGINT (Ctrl+C)
    while (1) {
        printf("Running... Press Ctrl+C to stop.\n");
        sleep(1);  // Wait for 1 second before printing again
    }
    return 0;
}

Try It Now

๐Ÿ”น Explanation

  • signal_handler(): The function that handles the SIGINT signal.
  • signal(SIGINT, signal_handler);: Registers the signal handler to catch the SIGINT signal.
  • The program continues running until the user presses Ctrl+C, at which point the signal handler is invoked and the program exits.

๐Ÿ“ Example 2: Handling SIGTERM (Termination Signal)

This example demonstrates how to handle the SIGTERM signal, which is commonly used to terminate a process.

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

void signal_handler(int signal) {
    printf("Caught signal %d: Termination signal (SIGTERM) received.\n", signal);
    exit(0);  // Exit the program after handling the signal
}

int main() {
    signal(SIGTERM, signal_handler);  // Catch SIGTERM
    while (1) {
        printf("Running... Send SIGTERM to terminate.\n");
        sleep(1);  // Wait for 1 second before printing again
    }
    return 0;
}

Try It Now

๐ŸŽฏ Key Takeaways

  • Signals are used to notify a process about events like interrupts or terminations.
  • The signal() function is used to catch and handle signals in C.
  • Common signals include SIGINT (Ctrl+C), SIGTERM (Termination), and many others.

๐Ÿ“ Practice Time!

Try modifying the signal handler function and experiment with different signals to better understand how signal handling works in C!