C signal() Function

The signal() function in C is a standard library function that sets a function to handle a particular signal. It is part of the C standard library (signal.h). This function is useful for handling asynchronous events like interrupts, termination requests, and other signals.

Table of Contents

  1. Introduction
  2. signal() Function Syntax
  3. Examples
    • Setting Up a Signal Handler
    • Using signal() to Handle SIGINT
  4. Real-World Use Case
  5. Conclusion

Introduction

The signal() function allows you to specify a function (a signal handler) that will be called when a specific signal occurs. Signals are software interrupts that can be sent to a process to notify it of various events, such as an interrupt from the user (Ctrl+C), a segmentation fault, or a termination request.

signal() Function Syntax

The syntax for the signal() function is as follows:

#include <signal.h>
void (*signal(int sig, void (*handler)(int)))(int);

Parameters:

  • sig: The signal number to be handled. Common signals include SIGINT, SIGTERM, SIGSEGV, etc.
  • handler: A pointer to the function that will handle the signal. This function must have a signature of void handler(int sig).

Returns:

  • The function returns the previous signal handler on success, or SIG_ERR on error.

Examples

Setting Up a Signal Handler

To demonstrate how to use signal() to set up a signal handler, we will write a simple program that handles the SIGINT signal (typically generated by pressing Ctrl+C).

Example

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

// Signal handler function
void handle_sigint(int sig) {
    printf("Caught signal %d (SIGINT). Exiting...\n", sig);
    _exit(0);
}

int main() {
    // Set up the signal handler for SIGINT
    if (signal(SIGINT, handle_sigint) == SIG_ERR) {
        perror("signal");
        return 1;
    }

    // Loop indefinitely
    while (1) {
        printf("Running... Press Ctrl+C to stop.\n");
        sleep(1);
    }

    return 0;
}

Output:

Running... Press Ctrl+C to stop.
Running... Press Ctrl+C to stop.
Caught signal 2 (SIGINT). Exiting...

Using signal() to Handle SIGINT

This example shows how to use signal() to handle the SIGINT signal, allowing the program to perform a clean exit when interrupted by the user.

Example

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

// Signal handler function
void handle_sigint(int sig) {
    printf("Caught signal %d (SIGINT). Cleaning up and exiting...\n", sig);
    // Perform any cleanup here
    _exit(0);
}

int main() {
    // Set up the signal handler for SIGINT
    if (signal(SIGINT, handle_sigint) == SIG_ERR) {
        perror("signal");
        return 1;
    }

    // Loop indefinitely
    while (1) {
        printf("Program is running. Press Ctrl+C to exit.\n");
        sleep(2);
    }

    return 0;
}

Output:

Program is running. Press Ctrl+C to exit.
Program is running. Press Ctrl+C to exit.
Caught signal 2 (SIGINT). Cleaning up and exiting...

Real-World Use Case

Handling Signals for Graceful Shutdown

In real-world applications, the signal() function can be used to handle signals for performing graceful shutdowns, allowing the program to release resources, save state, and clean up properly before exiting.

Example: Graceful Shutdown on SIGTERM

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

// Signal handler function for SIGTERM
void handle_sigterm(int sig) {
    printf("Caught signal %d (SIGTERM). Performing cleanup...\n", sig);
    // Perform any necessary cleanup here
    _exit(0);
}

int main() {
    // Set up the signal handler for SIGTERM
    if (signal(SIGTERM, handle_sigterm) == SIG_ERR) {
        perror("signal");
        return 1;
    }

    // Simulate long-running process
    printf("Process started. Send SIGTERM to stop.\n");
    while (1) {
        // Perform ongoing tasks
        sleep(5);
    }

    return 0;
}

Output:

Process started. Send SIGTERM to stop.
Caught signal 15 (SIGTERM). Performing cleanup...

Conclusion

The signal() function is essential for setting up signal handlers in C. It is useful in various applications, particularly for handling asynchronous events like interrupts and termination requests. By using signal(), you can ensure that your program can respond appropriately to signals and perform necessary cleanup operations.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare