sigaction in c

The sigaction function in C is used to change the action taken by a process on receipt of a specific signal. It allows the programmer to specify a custom handler function to be executed when a particular signal is received. The sigaction function is part of the signal handling mechanism in C and is defined in the <signal.h> header file.

Here is an example of how to use the sigaction function in C:

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

void signal_handler(int signum) {
    printf("Received signal: %d\n", signum);
}

int main() {
    struct sigaction sa;
    sa.sa_handler = signal_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;

    // Install the signal handler
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("Error setting up signal handler");
        return 1;
    }

    // Infinite loop to keep the program running
    while (1) {
        // Do some work here
    }

    return 0;
}

In this example, we define a signal handler function signal_handler that will be called when the SIGINT signal (generated by pressing Ctrl+C) is received. We then set up the sigaction structure sa with the appropriate values: the signal handler function, an empty signal mask, and no special flags. Finally, we call sigaction to install the signal handler.

Please note that this is just a basic example to demonstrate the usage of sigaction. In a real-world scenario, you may need to handle different signals and perform more complex actions in the signal handler function.