signal() Function Example in C Programming

In this source code example, we will see how to use the signal() function in C programming with an example.

signal() Function Overview

The signal() function in C is used to handle signals during a program's execution. Signals are asynchronous notifications delivered to processes by the operating system. By default, many signals terminate a program, but with the signal() function, we can customize this behavior. It's located in the <signal.h> header. 

Key Points: 

- The function requires the <signal.h> header. 

- Allows for custom signal handling or to ignore specific signals. 

- Common signals include SIGINT (sent by Ctrl+C) and SIGTERM (terminate signal). 

- Care is required when using signal(), as the handling of signals varies across different systems.

Source Code Example

#include <stdio.h>
#include <signal.h>  // Required for signal() and signal handling functions

// Custom handler for SIGINT signal (Ctrl+C)
void handle_sigint(int sig_num) {
    // Reset signal handler to default behavior
    signal(SIGINT, SIG_DFL);
    printf("\nCaught the SIGINT signal (%d). Exiting gracefully...\n", sig_num);
    exit(0);
}

int main() {
    // Set our handler for SIGINT
    signal(SIGINT, handle_sigint);
    printf("Running... Press Ctrl+C to exit\n");

    // Infinite loop to keep program running
    while (1) {
        // Simulate some ongoing process
    }

    return 0;
}

Output

Running... Press Ctrl+C to exit
[After pressing Ctrl+C]
Caught the SIGINT signal (2). Exiting gracefully...

Explanation

1. The program includes the necessary headers: stdio.h for I/O operations and signal.h for the signal() function and signal names.

2. The handle_sigint function is a custom handler for the SIGINT signal. When the user presses Ctrl+C, this handler will be invoked instead of the program's default behavior (which is termination).

3. Inside this handler, we reset the SIGINT signal handler to its default behavior using signal(SIGINT, SIG_DFL). This is a common practice to ensure that if Ctrl+C is pressed again, the default behavior occurs.

4. In main(), we set our custom handler for the SIGINT signal using signal(SIGINT, handle_sigint).

5. The program then enters an infinite loop, simulating some ongoing process.

6. When the user presses Ctrl+C, our custom handler is called, printing a message and exiting the program gracefully.

Using the signal() function in C allows developers to create more robust applications that can handle unexpected events or interruptions in a controlled manner. However, it's essential to use it judiciously and understand the platform-specific intricacies associated with signal handling.


Comments