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.
Using 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
The following is the complete code that uses 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 events and take appropriate action.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3