"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Gracefully Handle Ctrl-C Interrupts in C++ with the Sigaction Function?

How to Gracefully Handle Ctrl-C Interrupts in C++ with the Sigaction Function?

Published on 2024-11-17
Browse:780

How to Gracefully Handle Ctrl-C Interrupts in C   with the Sigaction Function?

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:

  • signum: to be processed The number of the signal, for Ctrl-C, SIGINT.
  • act: Specifies the action of the new signal handler.
  • oldact: Stores previous behavior.

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:

  • sa_handler: points to the handler function.
  • sa_mask: The signal mask to prevent during processing of this signal.
  • sa_flags: Additional flags, usually 0.

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.

Latest tutorial More>

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