Home >Backend Development >C++ >How can I intercept Ctrl C signals in C ?
Intercepting Control-C Signals in C
In the realm of programming, it's often necessary to capture keyboard events, such as the ubiquitous Ctrl C, which typically triggers program termination. This article addresses this specific need: how to intercept Ctrl C signals in C .
Capturing Ctrl C Events
In C , there are two primary methods for capturing Ctrl C events: signal and sigaction.
Using sigaction
The sigaction function provides a more reliable approach compared to signal, as it offers greater control and portability across different implementations. To use sigaction, follow these steps:
Include necessary headers:
#include <signal.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h>
Define a signal handler function:
void my_handler(int s){ printf("Caught signal %d\n",s); exit(1); }
In this handler, you can specify the actions to be performed when Ctrl C is pressed.
Configure the sigaction:
struct sigaction sigIntHandler; sigIntHandler.sa_handler = my_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL);
Here, you attach your signal handler to the Ctrl C signal (SIGINT) and specify signal-related settings.
Pause the program:
pause();
This function causes the program to wait for signals, including Ctrl C.
Example:
The following example demonstrates how to use sigaction to capture Ctrl C events:
#include <signal.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> void my_handler(int s){ printf("Caught signal %d\n",s); exit(1); } int main(int argc,char** argv) { struct sigaction sigIntHandler; sigIntHandler.sa_handler = my_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); pause(); return 0; }
When you run this program and press Ctrl C, it will print "Caught signal 2" and exit gracefully.
The above is the detailed content of How can I intercept Ctrl C signals in C ?. For more information, please follow other related articles on the PHP Chinese website!