In this comprehensive guide, we'll explore C Signal Examples, delving into the world of signal handling in C programming. By the end of this tutorial, you'll have a solid understanding of how to handle signals in your C programs. Let's get started! 🏃♂️
Introduction to Signal Handling
Signals in C Programming
C Signal Examples
Quiz 💡
Signals in C programming are asynchronous events generated by the system or by other processes. They are used to inform the process about some abnormal conditions or events such as a segmentation fault, interrupt, or a termination request.
Understanding signal handling is crucial as it allows your programs to react to such events gracefully, enhancing their robustness and reliability.
There are several predefined signals in C, some common ones are:
SIGINT: Generated when the user presses Ctrl + CSIGQUIT: Generated when the user presses Ctrl + \SIGSEGV: Generated when a segmentation fault occursSIGTERM: Generated to terminate a programA signal handler is a function that gets executed when a signal is caught by a program. To define a signal handler in C, you can use the signal() function:
#include <signal.h>
void handler(int signum) {
// Your code here
}
int main() {
signal(SIGINT, handler);
// Your main program
}In the above example, we've defined a signal handler handler() and registered it to handle the SIGINT signal.
Let's create a simple program that prints a message when the user presses Ctrl + C:
#include <stdio.h>
#include <signal.h>
void handler(int signum) {
printf("You pressed Ctrl + C\n");
}
int main() {
signal(SIGINT, handler);
printf("Press Ctrl + C to see the message\n");
while(1) {}
}In a more practical scenario, you might want to handle a signal to clean up resources before terminating a program. Here's an example where we save a modified file before exiting when receiving a SIGTERM signal:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void save_file(const char* filename) {
// Save the modified file here
}
void handler(int signum) {
if (signum == SIGTERM)
save_file("myfile.txt");
}
int main() {
signal(SIGTERM, handler);
// Modify the file here
exit(0);
}Which signal is generated when the user presses `Ctrl + C` in a C program?
That's all for now! With these examples and explanations, you should have a good grasp of C signal handling. Happy coding! 🎉