Intercepting Ctrl-C Events in C
Intercepting Ctrl-C Events is a necessary task in programming, especially when you want Gracefully respond to unexpected interruptions.
Use Sigaction
In C, it is more reliable to use the sigaction function to handle signals. The syntax is as follows:
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
Where:
In the example given by Thomas, the sigaction structure is as follows:
struct sigaction sigIntHandler; sigIntHandler.sa_handler = my_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0;
Where:
Use this sigaction structure with the SIGINT signal:
sigaction(SIGINT, &sigIntHandler, NULL);
Handler function
Finally, you need a handler function to respond to the signal. In the example, my_handler just prints a message and exits the program:
void my_handler(int s){ printf("Caught signal %d\n", s); exit(1); }
Full code
Here is the complete code using sigaction to capture Ctrl-C events :
#include#include #include #include 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; }
By using sigaction you can reliably catch Ctrl-C incident and take appropriate action.
The above is the detailed content of How to Gracefully Handle Ctrl-C Interrupts in C with the Sigaction Function?. For more information, please follow other related articles on the PHP Chinese website!