To efficiently catch a Ctrl-C event in C , the most reliable approach is to utilize the 'sigaction' function. It provides greater control and compatibility than the simple 'signal' function.
Implementing sigaction requires a structured approach:
#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; }
This approach provides a robust mechanism for handling Ctrl-C events in C , ensuring reliability and efficiency in various implementations.
The above is the detailed content of How Can `sigaction` Be Used to Handle Ctrl-C Events in C ?. For more information, please follow other related articles on the PHP Chinese website!