Welcome to the exciting world of C Signal Handling! In this lesson, we'll learn how to manage and respond to various signals in a C program. This knowledge is crucial for writing robust and flexible applications. 🎯
In C programming, a signal is an asynchronous event generated by the system or other processes. Signal handling allows your program to react to these events, enhancing its flexibility and robustness.
SIGINT (Ctrl+C) or SIGTERM signal.Here are some crucial signals that we will cover in this lesson:
SIGINT: Generated when the user presses Ctrl+CSIGTERM: Used to terminate a programSIGSEGV: Generated when a program attempts to access an invalid memory addressSIGFPE: Generated when a floating-point exception occursC provides two functions for signal handling: signal() and sigaction(). In this lesson, we'll focus on signal().
Let's create a simple signal handler function that prints a message when a signal is caught.
#include <signal.h>
#include <stdio.h>
void handler(int sig) {
printf("Caught signal: %d\n", sig);
}
int main() {
signal(SIGINT, handler);
printf("Press Ctrl+C to test signal handling\n");
// Your main program logic goes here
return 0;
}In the example above, we define a signal handler function handler() that prints a message when a signal is caught. Then, we use the signal() function to associate our signal handler with the SIGINT signal. When you run this program and press Ctrl+C, the message "Caught signal: 2" will be displayed, indicating that the SIGINT signal was handled.
In more complex scenarios, you may need to use sigaction() for signal handling. This function allows you to customize the behavior of the signal handler, including setting up a stack for the handler and specifying a flags parameter.
sigaction() 💡#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void handler(int sig, siginfo_t *info, void *context) {
printf("Caught signal: %d with data: %d\n", sig, info->si_int);
}
int main() {
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_sigaction = handler;
act.sa_flags = SA_SIGINFO;
sigemptyset(&act.sa_mask);
if (sigaction(SIGINT, &act, NULL) == -1) {
perror("Error setting signal handler");
return 1;
}
printf("Press Ctrl+C to test custom signal handling\n");
// Your main program logic goes here
return 0;
}In this example, we create a more advanced signal handler function that accepts additional data with the signal. We use sigaction() to set up our custom signal handler and specify the SA_SIGINFO flag to enable the passing of signal-specific information to the handler.
Which C function allows you to associate a signal handler with a specific signal?
We hope you enjoyed learning about C Signal Handling! Stay tuned for more exciting lessons on CodeYourCraft. Happy coding! 💻💻💻